<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CREbio - 生物信息学研究平台</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #2563eb;
            --secondary-color: #64748b;
            --success-color: #10b981;
            --warning-color: #f59e0b;
            --danger-color: #ef4444;
            --light-bg: #f8fafc;
            --card-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
            --border-color: #e2e8f0;
        }

        /* 配置区域样式 */
        .config-sections {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }

        .config-section {
            background: white;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            overflow: hidden;
            transition: all 0.3s ease;
        }

        .config-section:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            border-color: var(--primary-color);
        }

        .section-header {
            padding: 0.5rem 0.75rem;
            background: linear-gradient(135deg, var(--light-bg), #ffffff);
            border-bottom: 1px solid var(--border-color);
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: space-between;
            transition: all 0.3s ease;
        }

        .section-header:hover {
            background: linear-gradient(135deg, #f1f5f9, var(--light-bg));
        }

        .section-icon {
            font-size: 0.9rem;
            margin-right: 0.4rem;
        }

        .section-title {
            font-weight: 500;
            color: var(--secondary-color);
            flex: 1;
            font-size: 0.85rem;
        }

        .section-arrow {
            transition: transform 0.3s ease;
            color: var(--secondary-color);
        }

        .config-section.active .section-arrow {
            transform: rotate(180deg);
        }

        .section-content {
            padding: 0.6rem 0.75rem;
            display: none;
            background: white;
            font-size: 0.8rem;
        }

        .section-content.active {
            display: block;
            animation: slideDown 0.3s ease;
        }

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* 文件上传样式 */
        .file-upload-section {
            margin-bottom: 1rem;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            background: white;
            overflow: hidden;
        }

        .file-upload-area {
            padding: 2rem;
            border: 2px dashed var(--border-color);
            border-radius: 8px;
            text-align: center;
            transition: all 0.3s ease;
            cursor: pointer;
            background: #fafbfc;
        }

        .file-upload-area:hover {
            border-color: var(--primary-color);
            background: rgba(37, 99, 235, 0.02);
        }

        .file-upload-area.drag-over {
            border-color: var(--primary-color);
            background: rgba(37, 99, 235, 0.05);
            transform: scale(1.02);
        }

        .upload-content {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 1rem;
        }

        .upload-icon {
            font-size: 3rem;
            color: var(--secondary-color);
            opacity: 0.6;
        }

        .upload-text {
            text-align: center;
        }

        .upload-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: var(--secondary-color);
            margin-bottom: 0.5rem;
        }

        .upload-subtitle {
            font-size: 0.9rem;
            color: #6b7280;
        }

        .upload-button {
            background: var(--primary-color);
            color: white;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 6px;
            font-size: 0.9rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .upload-button:hover {
            background: #1d4ed8;
            transform: translateY(-1px);
        }

        .file-list {
            border-top: 1px solid var(--border-color);
            background: white;
        }

        .file-list-header {
            padding: 1rem;
            background: #f8fafc;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-weight: 600;
            color: var(--secondary-color);
        }

        .file-items {
            max-height: 200px;
            overflow-y: auto;
        }

        .file-item {
            padding: 0.75rem 1rem;
            border-bottom: 1px solid #f1f5f9;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: background 0.2s ease;
        }

        .file-item:hover {
            background: #f8fafc;
        }

        .file-info {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            flex: 1;
        }

        .file-icon {
            color: var(--primary-color);
            font-size: 1.1rem;
        }

        .file-details {
            display: flex;
            flex-direction: column;
        }

        .file-name {
            font-weight: 500;
            color: var(--secondary-color);
            font-size: 0.9rem;
        }

        .file-size {
            font-size: 0.8rem;
            color: #6b7280;
        }

        .file-actions {
            display: flex;
            gap: 0.5rem;
        }

        .btn-link {
            background: none;
            border: none;
            color: var(--primary-color);
            cursor: pointer;
            font-size: 0.85rem;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            transition: all 0.2s ease;
        }

        .btn-link:hover {
            background: rgba(37, 99, 235, 0.1);
        }

        .btn-danger {
            color: var(--danger-color);
        }

        .btn-danger:hover {
            background: rgba(239, 68, 68, 0.1);
        }

        .file-toggle-btn {
            background: none;
            border: 1px solid var(--border-color);
            color: var(--secondary-color);
            padding: 0.75rem;
            border-radius: 6px 0 0 6px;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            min-width: 45px;
        }

        .file-toggle-btn:hover {
            background: var(--light-bg);
            border-color: var(--primary-color);
            color: var(--primary-color);
        }

        .file-toggle-btn.active {
            background: var(--primary-color);
            border-color: var(--primary-color);
            color: white;
        }

        .input-controls {
            display: flex;
            flex: 1;
        }

        .input-controls .message-input {
            border-radius: 0 6px 6px 0;
            border-left: none;
        }

        /* 模型选项样式 */
        .model-options {
            display: flex;
            flex-direction: column;
            gap: 0.3rem;
            margin-bottom: 0.6rem;
        }

        .model-options label {
            display: flex;
            align-items: center;
            padding: 0.3rem 0.4rem;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.2s;
            font-size: 0.75rem;
        }

        .model-options label:hover {
            background: var(--light-bg);
        }

        .model-options input[type="radio"] {
            margin-right: 0.4rem;
            transform: scale(0.8);
        }

        /* 切换开关样式 */
        .toggle-switch {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 24px;
        }

        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: 0.4s;
            border-radius: 24px;
        }

        .slider:before {
            position: absolute;
            content: "";
            height: 18px;
            width: 18px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: 0.4s;
            border-radius: 50%;
        }

        input:checked + .slider {
            background-color: var(--primary-color);
        }

        input:checked + .slider:before {
            transform: translateX(26px);
        }

        /* 示例项目样式 */
        .example-item {
            background: var(--light-bg);
            border: 1px solid var(--border-color);
            border-radius: 4px;
            padding: 0.4rem 0.5rem;
            margin-bottom: 0.3rem;
            cursor: pointer;
            transition: all 0.2s ease;
            font-size: 0.7rem;
            line-height: 1.3;
        }

        .example-item:hover {
            background: #e2e8f0;
            border-color: var(--primary-color);
            transform: translateY(-1px);
        }

        .example-item:last-child {
            margin-bottom: 0;
        }

        /* 会话选择样式 */
        .session-select {
            width: 100%;
            padding: 0.5rem;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            background: white;
            font-size: 0.75rem;
        }

        .session-select:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
        }

        /* 反馈输入样式 */
        .feedback-input {
            width: 100%;
            min-height: 60px;
            padding: 0.5rem;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            resize: vertical;
            font-size: 0.75rem;
            margin-bottom: 0.6rem;
        }

        .feedback-input:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
        }

        .submit-btn {
            background: var(--primary-color);
            color: white;
            border: none;
            padding: 0.4rem 0.8rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .submit-btn:hover {
            background: #1d4ed8;
        }

        /* 使用统计样式 */
        .usage-stats {
            display: flex;
            flex-direction: column;
            gap: 0.4rem;
        }

        .stat-item {
            padding: 0.3rem 0;
            border-bottom: 1px solid var(--border-color);
            font-size: 0.7rem;
            color: var(--secondary-color);
        }

        .stat-item:last-child {
            border-bottom: none;
        }

        /* 免责声明样式 */
        .disclaimer-text {
            font-size: 0.7rem;
            line-height: 1.4;
        }

        .disclaimer-text p {
            margin-bottom: 0.4rem;
            color: var(--secondary-color);
        }

        .disclaimer-text p:last-child {
            margin-bottom: 0;
        }

        .disclaimer-text strong {
            color: var(--primary-color);
        }

        .disclaimer-text a {
            color: var(--primary-color);
            text-decoration: none;
        }

        .disclaimer-text a:hover {
            text-decoration: underline;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background-color: var(--light-bg);
            margin: 0;
            padding: 0;
        }

        /* 顶部导航栏 */
        .top-navbar {
            background: white;
            border-bottom: 1px solid var(--border-color);
            padding: 0.5rem 1rem;
            box-shadow: var(--card-shadow);
        }

        .navbar-brand {
            font-weight: 700;
            font-size: 1.2rem;
            color: var(--primary-color) !important;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 0.6rem;
        }

        .user-avatar {
            width: 28px;
            height: 28px;
            border-radius: 50%;
            background: var(--primary-color);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
            font-size: 0.75rem;
        }

        /* 余额相关样式已移除 */

        /* 主要内容区域 */
        .main-container {
            min-height: calc(100vh - 60px); /* 最小高度，允许内容延伸 */
            display: flex;
            flex-direction: column;
            padding: 0.25rem;
            gap: 0.25rem;
        }

        .content-area {
            display: flex;
            gap: 0.25rem;
            height: calc(100vh - 120px); /* 固定高度，底部留出间距 */
            margin-bottom: 20px; /* 与底部操作栏的间距 */
        }

        /* 左侧Co-pilot面板 */
        .copilot-panel {
            flex: 1; /* 改为弹性布局，平分宽度 */
            background: white;
            border-radius: 6px;
            box-shadow: var(--card-shadow);
            border: 1px solid var(--border-color);
            display: flex;
            flex-direction: column;
            height: 100%; /* 使用父容器的固定高度 */
            overflow: hidden;
            flex-shrink: 0; /* 防止收缩 */
        }

        .copilot-header {
            padding: 0.6rem 0.8rem;
            border-bottom: 1px solid var(--border-color);
            font-weight: 600;
            color: var(--secondary-color);
            font-size: 0.9rem;
        }

        .copilot-messages {
            flex: 1;
            padding: 0.6rem 0.8rem;
            overflow-y: auto;
        }

        .copilot-input {
            padding: 0.6rem 0.8rem;
            border-top: 1px solid var(--border-color);
        }

        .execution-header {
            padding: 0.6rem 0.8rem;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .execution-title {
            font-weight: 600;
            color: var(--secondary-color);
            font-size: 0.9rem;
        }

        .execution-messages {
            flex: 1;
            padding: 0.6rem 0.8rem;
            overflow-y: auto;
        }

        .execution-message {
            margin-bottom: 0.5rem;
            padding: 0.4rem 0.6rem;
            border-radius: 0.25rem;
            font-size: 0.85rem;
            line-height: 1.4;
        }

        .execution-message.log {
            background-color: #f8f9fa;
            border-left: 3px solid #6c757d;
        }

        .execution-message.reasoning {
            background-color: #e3f2fd;
            border-left: 3px solid #2196f3;
        }

        .execution-message.execution {
            background-color: #fff3e0;
            border-left: 3px solid #ff9800;
        }

        .execution-message.observation {
            background-color: #f3e5f5;
            border-left: 3px solid #9c27b0;
        }

        .execution-message.task {
            background-color: #e8f5e8;
            border-left: 3px solid #4caf50;
        }

        .execution-message.resource {
            background-color: #fff8e1;
            border-left: 3px solid #ffc107;
        }

        .execution-message.agent {
            background-color: #fce4ec;
        }

        /* 执行详情容器样式 */
        .execution-details-container {
            height: 100%;
            overflow-y: auto;
        }

        .execution-details-container .execution-details {
            background: #ffffff;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 15px;
            margin: 0;
            font-size: 0.85rem;
            line-height: 1.5;
        }

        .execution-details-container h4 {
            color: #495057;
            margin-bottom: 15px;
            font-size: 1rem;
            font-weight: 600;
            border-bottom: 2px solid #007bff;
            padding-bottom: 8px;
        }

        .execution-details-container ol {
            margin-left: 15px;
            padding-left: 5px;
        }

        .execution-details-container li {
            margin-bottom: 10px;
            padding: 8px;
            background: #f8f9fa;
            border-radius: 4px;
            border-left: 3px solid #007bff;
        }

        .execution-details-container strong {
            color: #495057;
        }

        .execution-details-container .text-muted {
            color: #6c757d !important;
        }

        .execution-details-container .text-success {
            color: #28a745 !important;
        }

        .execution-details-container .text-primary {
            color: #6f42c1 !important;
        }

        .execution-details-container .text-danger {
            color: #dc3545 !important;
            border-left: 3px solid #e91e63;
        }

        .execution-message.planning {
            background-color: #e0f2f1;
            border-left: 3px solid #009688;
        }

        .execution-message.success {
            background-color: #e8f5e8;
            border-left: 3px solid #4caf50;
            color: #2e7d32;
        }

        .execution-message.error {
            background-color: #ffebee;
            border-left: 3px solid #f44336;
            color: #c62828;
        }

        .execution-message.warning {
            background-color: #fff8e1;
            border-left: 3px solid #ff9800;
            color: #e65100;
        }

        .execution-message.info {
            background-color: #e3f2fd;
            border-left: 3px solid #2196f3;
            color: #0d47a1;
        }

        .execution-code pre {
            background-color: #f5f5f5;
            padding: 0.5rem;
            border-radius: 0.25rem;
            margin: 0.25rem 0;
            font-size: 0.8rem;
            overflow-x: auto;
        }

        .intelligent-summary {
            background-color: #e3f2fd;
            border: 1px solid #bbdefb;
            border-radius: 0.5rem;
            padding: 1rem;
            margin: 0.5rem 0;
            font-size: 0.9rem;
            line-height: 1.5;
        }

        .summary-item {
            background: var(--light-bg);
            border-radius: 4px;
            padding: 0.5rem 0.6rem;
            margin-bottom: 0.5rem;
            border-left: 2px solid var(--primary-color);
        }

        .summary-item:last-child {
            margin-bottom: 0;
        }

        .summary-title {
            font-weight: 600;
            font-size: 0.75rem;
            color: var(--secondary-color);
            margin-bottom: 0.3rem;
        }

        .summary-stats {
            display: flex;
            gap: 0.6rem;
            font-size: 0.65rem;
        }

        .summary-stat {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .summary-stat-value {
            font-weight: 600;
            color: var(--primary-color);
        }

        .summary-stat-label {
            color: var(--secondary-color);
            margin-top: 0.15rem;
        }

        /* 右侧执行面板 */
        .execution-panel {
            flex: 1; /* 平分宽度 */
            background: white;
            border-radius: 6px;
            box-shadow: var(--card-shadow);
            border: 1px solid var(--border-color);
            display: flex;
            flex-direction: column;
            height: 100%; /* 使用父容器的固定高度 */
            overflow: hidden;
        }

        .chat-header {
            padding: 0.6rem 0.8rem;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: between;
            align-items: center;
        }

        .chat-title {
            font-weight: 600;
            color: var(--secondary-color);
            font-size: 0.9rem;
        }

        .status-indicator {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            font-size: 0.875rem;
            font-weight: 500;
            padding: 0.5rem 0.75rem;
            background: rgba(255, 255, 255, 0.8);
            border-radius: 8px;
            border: 1px solid rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
        }

        .status-dot {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: var(--secondary-color);
            position: relative;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .status-dot::after {
            content: '';
            position: absolute;
            top: -2px;
            left: -2px;
            right: -2px;
            bottom: -2px;
            border-radius: 50%;
            background: inherit;
            opacity: 0.3;
            z-index: -1;
        }

        .status-dot.ready {
            background: linear-gradient(135deg, var(--success-color), #10b981);
            box-shadow: 0 2px 8px rgba(34, 197, 94, 0.3);
        }

        .status-dot.processing {
            background: linear-gradient(135deg, var(--warning-color), #f59e0b);
            animation: pulse 1.5s infinite;
            box-shadow: 0 2px 8px rgba(245, 158, 11, 0.3);
        }

        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }

        .chat-messages {
            flex: 1;
            padding: 0.6rem 0.8rem;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            gap: 0.6rem;
            min-height: 400px; /* 确保聊天框最小高度400px */
        }

        .message {
            max-width: 80%;
            padding: 0.5rem 0.7rem;
            border-radius: 8px;
            font-size: 0.75rem;
            line-height: 1.4;
        }

        .message.user {
            align-self: flex-end;
            background: var(--primary-color);
            color: white;
        }

        .message.assistant {
            align-self: flex-start;
            background: var(--light-bg);
            color: var(--secondary-color);
            border: 1px solid var(--border-color);
        }

        .message.system {
            align-self: center;
            background: var(--warning-color);
            color: white;
            font-size: 0.65rem;
            padding: 0.4rem 0.6rem;
        }

        .message.system.clickable {
            cursor: pointer;
            color: #007bff !important;
            text-decoration: underline;
        }

        .message.system.clickable:hover {
            color: #0056b3 !important;
            background: var(--primary-color);
        }

        /* 输入区域 */
        .chat-input {
            padding: 0.6rem 0.8rem;
            border-top: 1px solid var(--border-color);
        }

        .input-group {
            display: flex;
            gap: 0.4rem;
        }

        .message-input {
            flex: 1;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            padding: 0.5rem 0.6rem;
            font-size: 0.75rem;
            resize: none;
            min-height: 32px;
            max-height: 80px;
        }

        .message-input:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
        }

        .send-button {
            background: var(--primary-color);
            color: white;
            border: none;
            border-radius: 4px;
            padding: 0.5rem 0.8rem;
            font-size: 0.75rem;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .send-button:hover:not(:disabled) {
            background: #1d4ed8;
        }

        .send-button:disabled {
            background: var(--secondary-color);
            cursor: not-allowed;
        }

        /* 底部配置区域 */
        .config-panel {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            border: 1px solid var(--border-color);
            padding: 0.5rem;
            position: relative;
            overflow: visible;
            flex-shrink: 0;
        }
        
        .config-panel::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, var(--primary-color), #10b981, #f59e0b, #ef4444);
        }

        .config-tabs {
            display: flex;
            gap: 0.5rem;
            margin-bottom: 2rem;
            background: linear-gradient(135deg, var(--light-bg), #ffffff);
            border-radius: 12px;
            padding: 0.5rem;
            box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.06);
        }

        .config-tab {
            flex: 1;
            padding: 1rem 1.25rem;
            border: none;
            background: transparent;
            color: var(--secondary-color);
            font-size: 0.875rem;
            font-weight: 600;
            cursor: pointer;
            border-radius: 8px;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            text-align: center;
            position: relative;
            overflow: hidden;
        }
        
        .config-tab::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
            transition: left 0.5s;
        }
        
        .config-tab:hover::before {
            left: 100%;
        }

        .config-tab.active {
            background: linear-gradient(135deg, white, #f8fafc);
            color: var(--primary-color);
            box-shadow: 0 4px 12px rgba(37, 99, 235, 0.15), 0 2px 4px rgba(0, 0, 0, 0.1);
            transform: translateY(-1px);
        }

        .config-tab:hover:not(.active) {
            background: rgba(255, 255, 255, 0.7);
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .config-content {
            display: none;
            animation: fadeIn 0.4s ease-in-out;
        }

        .config-content.active {
            display: block;
        }
        
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .config-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
            gap: 1.5rem;
            margin-bottom: 1.5rem;
        }

        .config-item {
            display: flex;
            flex-direction: column;
            gap: 0.75rem;
            padding: 1.25rem;
            background: linear-gradient(135deg, #ffffff, #f8fafc);
            border-radius: 10px;
            border: 1px solid rgba(226, 232, 240, 0.8);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            overflow: hidden;
        }
        
        .config-item:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12), 0 4px 10px rgba(0, 0, 0, 0.08);
            border-color: var(--primary-color);
        }
        
        .config-item::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: linear-gradient(90deg, var(--primary-color), #10b981, #f59e0b);
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .config-item:hover::before {
            opacity: 1;
        }

        .config-label {
            font-size: 0.875rem;
            font-weight: 600;
            color: var(--secondary-color);
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .config-label i {
            color: var(--primary-color);
        }

        .config-section {
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 1rem;
            background: var(--light-bg);
        }

        .config-section-title {
            font-size: 0.875rem;
            font-weight: 600;
            color: var(--secondary-color);
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .status-indicator {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.375rem 1rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            border: 1px solid transparent;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            backdrop-filter: blur(10px);
        }

        .status-indicator.connected {
            background: linear-gradient(135deg, rgba(34, 197, 94, 0.15), rgba(16, 185, 129, 0.15));
            color: #059669;
            border-color: rgba(34, 197, 94, 0.2);
            box-shadow: 0 2px 8px rgba(34, 197, 94, 0.15);
        }

        .status-indicator.disconnected {
            background: linear-gradient(135deg, rgba(239, 68, 68, 0.15), rgba(220, 38, 38, 0.15));
            color: #dc2626;
            border-color: rgba(239, 68, 68, 0.2);
            box-shadow: 0 2px 8px rgba(239, 68, 68, 0.15);
        }

        .status-indicator.pending {
            background: linear-gradient(135deg, rgba(245, 158, 11, 0.15), rgba(217, 119, 6, 0.15));
            color: #d97706;
            border-color: rgba(245, 158, 11, 0.2);
            box-shadow: 0 2px 8px rgba(245, 158, 11, 0.15);
            animation: pulse-glow 2s infinite;
        }

        @keyframes pulse-glow {
            0%, 100% {
                box-shadow: 0 2px 8px rgba(245, 158, 11, 0.15);
            }
            50% {
                box-shadow: 0 4px 16px rgba(245, 158, 11, 0.3);
            }
        }

        .config-input {
            border: 2px solid var(--border-color);
            border-radius: 8px;
            padding: 0.75rem 1rem;
            font-size: 0.875rem;
            background: white;
            transition: all 0.3s ease;
            font-weight: 500;
        }

        .config-input:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.1), 0 2px 8px rgba(0, 0, 0, 0.1);
            transform: translateY(-1px);
        }
        
        .config-input:hover:not(:focus) {
            border-color: #cbd5e1;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        }

        .config-actions {
            display: flex;
            gap: 0.75rem;
            margin-top: 1.5rem;
            flex-wrap: wrap;
        }

        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-size: 0.875rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            border: 2px solid transparent;
            position: relative;
            overflow: hidden;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 120px;
        }
        
        .btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: left 0.5s;
        }
        
        .btn:hover::before {
            left: 100%;
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary-color), #1d4ed8);
            color: white;
            box-shadow: 0 4px 12px rgba(37, 99, 235, 0.3);
        }

        .btn-primary:hover {
            background: linear-gradient(135deg, #1d4ed8, #1e40af);
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(37, 99, 235, 0.4);
        }

        .btn-secondary {
            background: linear-gradient(135deg, var(--secondary-color), #475569);
            color: white;
            box-shadow: 0 4px 12px rgba(100, 116, 139, 0.3);
        }

        .btn-secondary:hover {
            background: linear-gradient(135deg, #475569, #334155);
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(100, 116, 139, 0.4);
        }

        .btn-outline {
            background: transparent;
            border: 2px solid var(--border-color);
            color: var(--secondary-color);
            position: relative;
            overflow: hidden;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .btn-outline::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
            transition: left 0.5s ease;
        }

        .btn-outline:hover {
            background: var(--light-bg);
            border-color: var(--primary-color);
            color: var(--primary-color);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
        }

        .btn-outline:hover::before {
            left: 100%;
        }

        .btn-outline:active {
            transform: translateY(0);
            box-shadow: 0 2px 6px rgba(59, 130, 246, 0.1);
        }

        /* 认证界面 */
        .auth-container {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }

        .auth-modal {
            background: white;
            border-radius: 8px;
            padding: 2rem;
            width: 100%;
            max-width: 400px;
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
        }

        .auth-title {
            font-size: 1.5rem;
            font-weight: 700;
            text-align: center;
            margin-bottom: 1.5rem;
            color: var(--secondary-color);
        }

        .auth-form {
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }

        .form-group {
            display: flex;
            flex-direction: column;
            gap: 0.75rem;
            margin-bottom: 1.25rem;
        }

        .form-label {
            font-size: 0.875rem;
            font-weight: 600;
            color: var(--text-color);
            margin-bottom: 0.25rem;
        }

        .form-input {
            border: 2px solid var(--border-color);
            border-radius: 8px;
            padding: 0.875rem 1rem;
            font-size: 0.875rem;
            background: white;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            font-weight: 500;
        }

        .form-input:hover:not(:focus) {
            border-color: var(--primary-color);
            background: rgba(59, 130, 246, 0.02);
        }

        .form-input:focus {
            outline: none;
            border-color: var(--primary-color);
            background: white;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1), 0 4px 12px rgba(59, 130, 246, 0.15);
            transform: translateY(-1px);
        }

        .auth-button {
            background: linear-gradient(135deg, var(--primary-color), #4f46e5);
            color: white;
            border: none;
            border-radius: 8px;
            padding: 0.875rem 1.5rem;
            font-size: 0.875rem;
            font-weight: 600;
            cursor: pointer;
            margin-top: 1rem;
            position: relative;
            overflow: hidden;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .auth-button::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: left 0.5s ease;
        }

        .auth-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(59, 130, 246, 0.4);
        }

        .auth-button:hover::before {
            left: 100%;
        }

        .auth-button:active {
            transform: translateY(0);
            box-shadow: 0 3px 10px rgba(59, 130, 246, 0.3);
        }

        .auth-button:hover {
            background: #1d4ed8;
        }

        .auth-switch {
            text-align: center;
            margin-top: 1rem;
            font-size: 0.875rem;
            color: var(--secondary-color);
        }

        .auth-switch a {
            color: var(--primary-color);
            text-decoration: none;
            font-weight: 500;
        }

        .auth-switch a:hover {
            text-decoration: underline;
        }

        .error-message {
            background: #fef2f2;
            color: var(--danger-color);
            padding: 0.75rem;
            border-radius: 4px;
            font-size: 0.875rem;
            border: 1px solid #fecaca;
            margin-top: 1rem;
            animation: shake 0.5s ease-in-out;
        }

        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            25% { transform: translateX(-5px); }
            75% { transform: translateX(5px); }
        }

        /* 表单提示样式 */
        .form-hint {
            font-size: 0.75rem;
            color: #6b7280;
            margin-top: 0.25rem;
            line-height: 1.4;
        }

        .password-requirements {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            padding: 0.75rem;
            margin-top: 0.5rem;
        }

        .requirement-title {
            font-weight: 600;
            color: #374151;
            margin-bottom: 0.5rem;
            font-size: 0.8rem;
        }

        .requirement-item {
            font-size: 0.75rem;
            color: #6b7280;
            margin-bottom: 0.25rem;
            transition: color 0.3s ease;
        }

        .requirement-item.valid {
            color: #10b981;
        }

        .requirement-item.invalid {
            color: #ef4444;
        }

        /* 进度条和状态显示 */
        .progress-container {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 0.5rem 0;
        }

        .progress-bar {
            flex: 1;
            height: 10px;
            background: linear-gradient(90deg, #f1f5f9, #e2e8f0);
            border-radius: 8px;
            overflow: hidden;
            position: relative;
            box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, var(--primary-color), #10b981, #06d6a0);
            border-radius: 8px;
            transition: width 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            overflow: hidden;
        }

        .progress-fill::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
            animation: shimmer 2s infinite;
        }

        @keyframes shimmer {
            0% { transform: translateX(-100%); }
            100% { transform: translateX(100%); }
        }

        .progress-text {
            font-size: 0.875rem;
            font-weight: 600;
            color: var(--text-color);
            min-width: 65px;
            text-align: right;
            background: linear-gradient(135deg, var(--primary-color), #10b981);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .status-value {
            display: flex;
            align-items: center;
            font-weight: 600;
            color: var(--text-color);
            padding: 0.25rem 0.75rem;
            background: linear-gradient(135deg, rgba(59, 130, 246, 0.1), rgba(16, 185, 129, 0.1));
            border-radius: 6px;
            border: 1px solid rgba(59, 130, 246, 0.2);
        }

        .status-value span {
            font-size: 1rem;
            background: linear-gradient(135deg, var(--primary-color), #10b981);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        /* 配置区域增强样式 */
        .config-section {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
        }

        .config-section-title {
            font-weight: 600;
            color: var(--primary-color);
            margin-bottom: 0.75rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .config-label {
            font-weight: 500;
            color: #495057;
            margin-bottom: 0.25rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .content-area {
                flex-direction: column;
            }

            .summary-panel {
                width: 100%;
                height: 200px;
            }

            .config-grid {
                grid-template-columns: 1fr;
            }
        }

        /* 隐藏类 */
        .hidden {
            display: none !important;
        }

        /* 消息类型样式 */
        .log-message {
            background: #f8f9fa;
            border-left: 3px solid #6c757d;
            padding: 0.5rem;
            margin: 0.25rem 0;
            font-family: 'Courier New', monospace;
            font-size: 0.875rem;
            color: #495057;
        }

        .reasoning-message {
            background: linear-gradient(135deg, #e3f2fd, #f3e5f5);
            border-left: 3px solid #2196f3;
            padding: 0.75rem;
            margin: 0.5rem 0;
            border-radius: 4px;
            color: #1565c0;
        }

        .execution-message {
            background: #f1f8e9;
            border-left: 3px solid #4caf50;
            padding: 0.75rem;
            margin: 0.5rem 0;
            border-radius: 4px;
            color: #2e7d32;
        }

        .execution-message pre {
            background: #263238;
            color: #ffffff;
            padding: 0.75rem;
            border-radius: 4px;
            margin: 0.5rem 0;
            overflow-x: auto;
            font-size: 0.875rem;
        }

        .observation-message {
            background: #fff3e0;
            border-left: 3px solid #ff9800;
            padding: 0.75rem;
            margin: 0.5rem 0;
            border-radius: 4px;
            color: #e65100;
        }

        .solution-message {
            background: #e8f5e8;
            border-left: 3px solid #4caf50;
            padding: 0.75rem;
            margin: 0.5rem 0;
            border-radius: 4px;
            color: #1b5e20;
            font-weight: 500;
        }

        .task-start-message {
            background: linear-gradient(135deg, #e1f5fe, #f3e5f5);
            border-left: 3px solid #00bcd4;
            padding: 0.75rem;
            margin: 0.5rem 0;
            border-radius: 4px;
            color: #006064;
            font-weight: 600;
        }

        .resource-retrieval-message {
            background: #fafafa;
            border-left: 3px solid #9e9e9e;
            padding: 0.75rem;
            margin: 0.5rem 0;
            border-radius: 4px;
            color: #424242;
        }

        .agent-start-message {
            background: linear-gradient(135deg, #f3e5f5, #e8eaf6);
            border-left: 3px solid #9c27b0;
            padding: 0.75rem;
            margin: 0.5rem 0;
            border-radius: 4px;
            color: #4a148c;
            font-weight: 600;
        }

        .planning-message {
            background: #fff8e1;
            border-left: 3px solid #ffc107;
            padding: 0.75rem;
            margin: 0.5rem 0;
            border-radius: 4px;
            color: #f57f17;
        }

        /* 复杂度指示器样式 */
        .complexity-indicator {
            margin-top: 0.5rem;
            padding: 0.75rem 1rem;
            border-radius: 8px;
            border: 1px solid var(--border-color);
            background: linear-gradient(135deg, #f8fafc, #ffffff);
            transition: all 0.3s ease;
            animation: fadeInUp 0.3s ease;
        }

        .complexity-indicator.simple {
            border-color: #10b981;
            background: linear-gradient(135deg, #ecfdf5, #f0fdf4);
        }

        .complexity-indicator.complex {
            border-color: #3b82f6;
            background: linear-gradient(135deg, #eff6ff, #f0f9ff);
        }

        .indicator-content {
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .indicator-icon {
            font-size: 1.1rem;
            color: #10b981;
            transition: color 0.3s ease;
        }

        .complexity-indicator.complex .indicator-icon {
            color: #3b82f6;
        }

        .indicator-text {
            font-weight: 600;
            font-size: 0.875rem;
            color: #374151;
        }

        .indicator-desc {
            font-size: 0.75rem;
            color: #6b7280;
            margin-left: auto;
        }

        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }


    </style>
</head>
<body>
    <!-- 认证界面 -->
    <div id="authContainer" class="auth-container">
        <div class="auth-modal">
            <h2 class="auth-title">欢迎使用 CREbio</h2>
            
            <!-- 登录表单 -->
            <div id="loginForm" class="auth-form">
                <div class="form-group">
                    <label class="form-label">用户名或邮箱</label>
                    <input type="text" id="loginUsername" class="form-input" placeholder="请输入用户名或邮箱">
                </div>
                <div class="form-group">
                    <label class="form-label">密码</label>
                    <input type="password" id="loginPassword" class="form-input" placeholder="请输入密码">
                </div>
                <button type="button" class="auth-button" onclick="login()">登录</button>
                <div class="auth-switch">
                    还没有账号？<a href="#" onclick="showRegister()">立即注册</a>
                </div>
            </div>

            <!-- 注册表单 -->
            <div id="registerForm" class="auth-form hidden">
                <div class="form-group">
                    <label class="form-label">用户名</label>
                    <input type="text" id="registerUsername" class="form-input" placeholder="请输入用户名">
                    <div class="form-hint">用户名需要3-80个字符，只能包含字母、数字、下划线和连字符</div>
                </div>
                <div class="form-group">
                    <label class="form-label">邮箱</label>
                    <input type="email" id="registerEmail" class="form-input" placeholder="请输入邮箱">
                </div>
                <div class="form-group">
                    <label class="form-label">密码</label>
                    <input type="password" id="registerPassword" class="form-input" placeholder="请输入密码">
                    <div class="form-hint password-requirements">
                        <div class="requirement-title">密码要求：</div>
                        <div class="requirement-item" id="req-length">• 至少8个字符</div>
                        <div class="requirement-item" id="req-letter">• 包含字母</div>
                        <div class="requirement-item" id="req-number">• 包含数字</div>
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">确认密码</label>
                    <input type="password" id="registerConfirmPassword" class="form-input" placeholder="请再次输入密码">
                </div>
                <button type="button" class="auth-button" onclick="register()">注册</button>
                <div class="auth-switch">
                    已有账号？<a href="#" onclick="showLogin()">立即登录</a>
                </div>
            </div>

            <!-- 错误消息 -->
            <div id="authError" class="error-message hidden"></div>
        </div>
    </div>

    <!-- 主应用界面 -->
    <div id="mainApp" class="hidden">
        <!-- 顶部导航栏 -->
        <nav class="top-navbar">
            <div class="d-flex justify-content-between align-items-center">
                <div class="navbar-brand">
                    <i class="fas fa-dna me-2"></i>CREbio
                </div>
                <div class="user-info flex-grow-1 mx-3">
                    <div class="d-flex align-items-center justify-content-between">
                        <div class="user-welcome">
                            <div class="d-flex align-items-center">
                                <div class="user-avatar me-2" id="userAvatar">U</div>
                                <div>
                                    <div class="fw-semibold" id="welcomeMessage">Welcome to CREbio, user! 👋</div>
                                    <div class="small text-muted" id="quotaInfo">Weekly quota: 0/100 requests remaining (renews 2025-08-25)</div>
                                </div>
                            </div>
                            <div class="mt-1" id="importantNotice">
                                <small class="text-warning">
                                    <i class="fas fa-exclamation-triangle me-1"></i>
                                    <strong>Important:</strong> AI models may hallucinate occasionally. Please examine the entire execution trace closely if you want to utilize the results.
                                </small>
                            </div>
                        </div>
                        <!-- 余额显示区域已移除 -->
                    </div>
                </div>
                <button class="btn btn-outline-secondary btn-sm" onclick="logout()">
                    <i class="fas fa-sign-out-alt"></i> 退出
                </button>
            </div>
        </nav>

        <!-- 主要内容区域 -->
        <div class="main-container">
            <!-- 内容区域 -->
            <div class="content-area">
                <!-- 左侧Co-pilot对话面板 -->
                <div class="copilot-panel">
                    <div class="copilot-header">
                        <i class="fas fa-robot me-2"></i>Co-pilot
                    </div>
                    <div class="copilot-messages" id="copilotMessages">
                        <div class="message system">
                            欢迎使用 CREbio Co-pilot！我是您的智能助手，可以帮助您进行生物信息学研究。
                        </div>
                    </div>
                    <div class="copilot-input">
                        <!-- 文件上传区域 -->
                        <div class="file-upload-section" id="fileUploadSection" style="display: none;">
                            <div class="file-upload-area" id="fileUploadArea" ondrop="handleFileDrop(event)" ondragover="handleDragOver(event)" ondragleave="handleDragLeave(event)">
                                <div class="upload-content">
                                    <i class="fas fa-cloud-upload-alt upload-icon"></i>
                                    <div class="upload-text">
                                        <div class="upload-title">拖拽文件到此处或点击选择</div>
                                        <div class="upload-subtitle">支持 CSV, JSON, FASTA, FASTQ, VCF, TXT, PDF, 图片等格式</div>
                                    </div>
                                    <input type="file" id="fileInput" multiple accept=".txt,.pdf,.png,.jpg,.jpeg,.gif,.csv,.json,.xlsx,.xls,.fasta,.fastq,.vcf,.tsv" style="display: none;" onchange="handleFileSelect(event)">
                                    <button class="upload-button" onclick="document.getElementById('fileInput').click()">
                                        <i class="fas fa-folder-open"></i> 选择文件
                                    </button>
                                </div>
                            </div>
                            <div class="file-list" id="fileList" style="display: none;">
                                <div class="file-list-header">
                                    <span><i class="fas fa-files"></i> 已上传文件</span>
                                    <button class="btn-link" onclick="refreshFileList()">
                                        <i class="fas fa-sync-alt"></i> 刷新
                                    </button>
                                </div>
                                <div class="file-items" id="fileItems"></div>
                            </div>
                        </div>
                        
                        <div class="input-group">
                            <div class="input-controls">
                                <button class="file-toggle-btn" id="fileToggleBtn" onclick="toggleFileUpload()" title="文件上传">
                                    <i class="fas fa-paperclip"></i>
                                </button>
                                <textarea 
                                    id="copilotInput" 
                                    class="message-input" 
                                    placeholder="请输入您的问题..."
                                    onkeypress="handleCopilotKeyPress(event)"
                                    oninput="updateComplexityIndicator()"
                                ></textarea>
                            </div>
                            <button id="copilotSendButton" class="send-button" onclick="sendCopilotMessage()" disabled>
                                <i class="fas fa-paper-plane"></i>
                            </button>
                        </div>
                        <div class="complexity-indicator" id="complexityIndicator" style="display: none;">
                            <div class="indicator-content">
                                <i class="indicator-icon fas fa-comments" id="indicatorIcon"></i>
                                <span class="indicator-text" id="indicatorText">简单对话模式</span>
                                <span class="indicator-desc" id="indicatorDesc">快速响应，适合问候和简单问题</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 右侧执行过程面板 -->
                <div class="execution-panel" id="executionPanel">
                    <div class="execution-header">
                        <div class="execution-title">
                            <i class="fas fa-cogs me-2"></i>执行过程
                        </div>
                        <div class="status-indicator">
                            <div class="status-dot" id="statusDot"></div>
                            <span id="statusText">就绪</span>
                        </div>
                    </div>
                    <div class="execution-messages" id="executionMessages">
                        <div class="text-center text-muted py-4">
                            <i class="fas fa-play-circle fa-2x mb-2"></i>
                            <div>等待执行复杂任务...</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 底部配置区域 -->
            <div class="config-panel">
                <div class="config-sections">
                    <div class="config-section" onclick="toggleSection('tips')">
                        <div class="section-header">
                            <span class="section-icon">✨</span>
                            <span class="section-title">提示 CREbio 的技巧</span>
                            <i class="fas fa-chevron-down section-arrow"></i>
                        </div>
                        <div class="section-content" id="tips-content">
                            <p>最适合复杂研究任务（数据分析、协议设计、深度研究），不适合简单的问答。</p>
                            <p>描述您希望如何执行任务的逐步说明，以便您应该作为研究助手指定关键参数、阈值和需要注意的事项。</p>
                            <p>该Web平台是一个研究演示，具有有限的计算资源（1.5TB RAM，32个vCPU，无GPU——可以完成所有无GPU参与的生信分析）——请避免运行计算密集型任务。</p>
                        </div>
                    </div>
                    
                    <div class="config-section" onclick="toggleSection('examples')">
                        <div class="section-header">
                            <span class="section-icon">💡</span>
                            <span class="section-title">研究问题示例</span>
                            <i class="fas fa-chevron-down section-arrow"></i>
                        </div>
                        <div class="section-content" id="examples-content">
                            <div class="example-item" onclick="copyExampleToInput(this)">不同的扰动如何影响PeptideSanja2021 TnP-1细胞数据集中的蛋白质表达？</div>
                            <div class="example-item" onclick="copyExampleToInput(this)">我有一个名为plentiCRISPR v2（简称）的质粒，我想克隆一个CRISPR sgRNA靶向人类B2M到这个质粒中。您能保存最终组装的质粒图谱到*fasta中，并显示逐步指导我应该如何执行克隆吗？</div>
                            <div class="example-item" onclick="copyExampleToInput(this)">我有一个患有以下表型的患者：智力障碍、癫痫和面部畸形。您能帮我识别潜在的遗传原因吗？</div>
                        </div>
                    </div>
                    
                    <div class="config-section" onclick="toggleSection('sessions')">
                        <div class="section-header">
                            <span class="section-icon">📊</span>
                            <span class="section-title">加载会话历史记录并导出和下载</span>
                            <i class="fas fa-chevron-down section-arrow"></i>
                        </div>
                        <div class="section-content" id="sessions-content">
                            <select class="session-select" id="sessionSelect" onchange="onSessionSelected()" onclick="event.stopPropagation()">
                                <option value="">Select a Session to Download Logs</option>
                            </select>
                            <div class="session-actions" style="margin-top: 10px; display: none;" id="sessionActions" onclick="event.stopPropagation()">
                                <button class="btn btn-primary btn-sm" onclick="downloadSession()" style="margin-right: 5px;">
                                    <i class="fas fa-download"></i> 下载会话
                                </button>
                                <button class="btn btn-info btn-sm" onclick="loadSessionHistory()">
                                    <i class="fas fa-history"></i> 加载历史
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="config-section" onclick="toggleSection('models')">
                        <div class="section-header">
                            <span class="section-icon">🧠</span>
                            <span class="section-title">模型和问题路由选择</span>
                            <i class="fas fa-chevron-down section-arrow"></i>
                        </div>
                        <div class="section-content" id="models-content">
                            <div class="model-options">
                                <label><input type="radio" name="model" value="claude-sonnet-4-20250514" checked> Claude Sonnet 4</label>
                                <label><input type="radio" name="model" value="gpt-4"> GPT-4</label>
                                <label><input type="radio" name="model" value="gpt-4o"> GPT-4o</label>
                                <label><input type="radio" name="model" value="gpt-4o-mini"> GPT-4o Mini</label>
                            </div>
                            <p>启用问题路由以自动选择最佳模型</p>
                            <label class="toggle-switch">
                                <input type="checkbox" id="questionRouting">
                                <span class="slider"></span>
                            </label>
                        </div>
                    </div>
                    
                    <div class="config-section" onclick="toggleSection('feedback')">
                        <div class="section-header">
                            <span class="section-icon">📝</span>
                            <span class="section-title">提供反馈</span>
                            <i class="fas fa-chevron-down section-arrow"></i>
                        </div>
                        <div class="section-content" id="feedback-content">
                            <textarea class="feedback-input" placeholder="在此处输入您的反馈..."></textarea>
                            <button class="submit-btn">提交</button>
                        </div>
                    </div>
                    
                    <div class="config-section" onclick="toggleSection('usage')">
                        <div class="section-header">
                            <span class="section-icon">💰</span>
                            <span class="section-title">使用情况统计</span>
                            <i class="fas fa-chevron-down section-arrow"></i>
                        </div>
                        <div class="section-content" id="usage-content">
                            <div class="usage-stats">
                                <div class="stat-item">本周调用次数: <span id="weeklyRequests">0</span>/<span id="weeklyLimit">100</span></div>
                                <div class="stat-item">输入Tokens: <span id="inputTokens">0</span></div>
                                <div class="stat-item">输出Tokens: <span id="outputTokens">0</span></div>
                                <div class="stat-item">总Token使用: <span id="totalTokens">0</span></div>
                                <div class="stat-item">API元点消耗: <span id="apiPoints">0.00</span> <small style="color: #666; font-size: 0.8em;">(输入Tokens÷26.6 + 输出Tokens÷133.2)</small></div>
                                <div class="stat-item">总费用: $<span id="totalCost">0.00</span></div>
                                <div class="stat-item">平均每次调用费用: $<span id="avgCost">0.00</span></div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="config-section" onclick="toggleSection('disclaimer')">
                        <div class="section-header">
                            <span class="section-icon">⚠️</span>
                            <span class="section-title">免责声明 & 数据安全 & 隐私</span>
                            <i class="fas fa-chevron-down section-arrow"></i>
                        </div>
                        <div class="section-content" id="disclaimer-content">
                            <div class="disclaimer-text">
                                <p><strong>重要信息</strong></p>
                                <p><strong>人工智能限制:</strong> 这是一个人工智能助手，具备生物学方面的知识，但请注意其局限性，也请避免其在实验室中的实际应用。</p>
                                <p><strong>无医疗建议:</strong> 所提供的内容仅供研究参考，不应被视为医疗建议或诊断。</p>
                                <p><strong>隐私保护:</strong> 请勿在对话中包含敏感的个人健康信息（PHI）或个人身份信息。</p>
                                <p><strong>数据安全:</strong> 我们对用户隐私负责，代理服务器不会存储您的对话或个人信息。</p>
                                <p><strong>数据隐私:</strong> 我们对用户隐私负责，代理服务器不会存储您的对话或个人信息，我们不会将您的第三方信息，我们不会将您的对话内容分享给第三方或用于其他目的，请参考我们的<a href="#">隐私政策和服务条款</a>以获取更多信息。</p>
                            </div>
                        </div>
                    </div>
                </div>






            </div>
        </div>
    </div>



    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 全局变量
        let authToken = localStorage.getItem('authToken');
        let currentUser = null;
        // 移除了currentSessionCost变量，改为使用全局统计
        let abortController = null;
        let isAgentInitialized = false;
        let currentSessionId = null; // 跟踪当前会话ID

        // 页面加载时检查认证状态
        document.addEventListener('DOMContentLoaded', function() {
            console.log('页面加载完成，开始检查初始化状态');
            // 首先检查自动初始化状态
            checkAutoInitialization();
            
            // 绑定错误清除事件
            bindErrorClearEvents();
            
            if (authToken) {
                checkAuthStatus();
            } else {
                showAuthContainer();
            }

            // 温度滑块事件
            const temperatureSlider = document.getElementById('temperature');
            if (temperatureSlider) {
                temperatureSlider.addEventListener('input', function() {
                    const temperatureValue = document.getElementById('temperatureValue');
                    if (temperatureValue) {
                        temperatureValue.textContent = this.value;
                    }
                });
            }
        });

        // 切换配置部分
        function toggleSection(sectionId) {
            const section = document.querySelector(`[onclick="toggleSection('${sectionId}')"]`);
            const content = document.getElementById(sectionId + '-content');
            
            if (content.style.display === 'none' || content.style.display === '') {
                content.style.display = 'block';
                content.classList.add('active');
                section.classList.add('active');
            } else {
                content.style.display = 'none';
                content.classList.remove('active');
                section.classList.remove('active');
            }
        }

        // 显示认证界面
        function showAuthContainer() {
            document.getElementById('authContainer').classList.remove('hidden');
            document.getElementById('mainApp').classList.add('hidden');
        }

        // 显示主应用
        function showMainApp() {
            console.log('显示主应用，准备加载会话历史');
            document.getElementById('authContainer').classList.add('hidden');
            document.getElementById('mainApp').classList.remove('hidden');
            
            // 加载可用的会话列表
            if (authToken) {
                console.log('有认证token，开始加载会话历史');
                loadAvailableSessions();
            } else {
                console.log('没有认证token，跳过加载会话历史');
            }
        }

        // 显示登录表单
        function showLogin() {
            document.getElementById('loginForm').classList.remove('hidden');
            document.getElementById('registerForm').classList.add('hidden');
            hideAuthError();
        }

        // 显示注册表单
        function showRegister() {
            document.getElementById('loginForm').classList.add('hidden');
            document.getElementById('registerForm').classList.remove('hidden');
            hideAuthError();
        }

        // 显示认证错误
        function showAuthError(message, errors = null) {
            const errorDiv = document.getElementById('authError');
            
            // 构建错误消息
            let errorContent = message;
            if (errors && Array.isArray(errors) && errors.length > 0) {
                errorContent += '<br><ul style="margin: 0.5rem 0 0 1rem; padding: 0;">';
                errors.forEach(error => {
                    errorContent += `<li style="margin-bottom: 0.25rem;">${error}</li>`;
                });
                errorContent += '</ul>';
            }
            
            errorDiv.innerHTML = errorContent;
            errorDiv.classList.remove('hidden');
            
            // 添加震动效果
            errorDiv.style.animation = 'none';
            setTimeout(() => {
                errorDiv.style.animation = 'shake 0.5s ease-in-out';
            }, 10);
            
            // 自动隐藏错误消息（5秒后）
            setTimeout(() => {
                hideAuthError();
            }, 5000);
        }

        // 隐藏认证错误
        function hideAuthError() {
            const errorDiv = document.getElementById('authError');
            errorDiv.classList.add('hidden');
            errorDiv.innerHTML = '';
        }
        
        // 清除错误消息当用户开始输入时
        function bindErrorClearEvents() {
            const inputs = ['loginUsername', 'loginPassword', 'registerUsername', 'registerEmail', 'registerPassword', 'registerConfirmPassword'];
            inputs.forEach(inputId => {
                const input = document.getElementById(inputId);
                if (input) {
                    input.addEventListener('input', hideAuthError);
                }
            });
        }

        // 检查认证状态
        async function checkAuthStatus() {
            console.log('开始检查认证状态，当前token:', authToken ? '存在' : '不存在');
            try {
                const response = await fetch('/api/auth/status', {
                    headers: {
                        'Authorization': `Bearer ${authToken}`
                    }
                });
                
                console.log('认证状态API响应状态:', response.status);

                if (response.ok) {
                    const data = await response.json();
                    console.log('认证成功，用户信息:', data.user);
                    currentUser = data.user;
                    // 先显示基本用户信息（不包含配额）
                    updateUserInfo();
                    showMainApp();
                    // 获取用户统计信息并更新配额显示
                    await fetchUserStats();
                    // 检查自动初始化状态
                    checkAutoInitialization();
                } else {
                    console.log('认证失败，清除token并显示登录界面');
                    localStorage.removeItem('authToken');
                    authToken = null;
                    showAuthContainer();
                }
            } catch (error) {
                console.error('检查认证状态失败:', error);
                showAuthContainer();
            }
        }

        // 登录
        async function login() {
            const username = document.getElementById('loginUsername').value.trim();
            const password = document.getElementById('loginPassword').value;
            
            console.log('开始登录，用户名:', username);

            if (!username || !password) {
                showAuthError('请填写完整的登录信息');
                return;
            }

            try {
                const response = await fetch('/api/auth/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ username, password })
                });
                
                console.log('登录API响应状态:', response.status);
                const data = await response.json();
                console.log('登录API返回数据:', data);

                if (data.success) {
                    console.log('登录成功，获得token:', data.token ? '存在' : '不存在');
                    authToken = data.token;
                    localStorage.setItem('authToken', authToken);
                    currentUser = data.user;
                    // 先显示基本用户信息（不包含配额）
                    updateUserInfo();
                    showMainApp();
                    // 获取用户统计信息并更新配额显示
                    await fetchUserStats();
                    // 检查自动初始化状态
                    checkAutoInitialization();
                } else {
                    console.log('登录失败:', data.message);
                    // 处理服务器返回的错误信息
                    let errorMessage = data.message || '登录失败';
                    let errorDetails = null;
                    
                    // 如果服务器返回了详细的错误信息
                    if (data.errors && Array.isArray(data.errors)) {
                        errorDetails = data.errors;
                    } else if (data.details && Array.isArray(data.details)) {
                        errorDetails = data.details;
                    }
                    
                    // 根据常见错误类型提供更友好的提示
                    if (errorMessage.includes('用户不存在') || errorMessage.includes('user not found')) {
                        errorMessage = '用户名不存在，请检查用户名或注册新账户';
                    } else if (errorMessage.includes('密码错误') || errorMessage.includes('invalid password')) {
                        errorMessage = '密码错误，请重新输入';
                    } else if (errorMessage.includes('账户被锁定') || errorMessage.includes('account locked')) {
                        errorMessage = '账户已被锁定，请联系管理员';
                    }
                    
                    showAuthError(errorMessage, errorDetails);
                }
            } catch (error) {
                console.error('登录失败:', error);
                showAuthError('网络连接失败，请检查网络后重试');
            }
        }

        // 密码实时验证
        function validatePassword(password) {
            const requirements = {
                length: password.length >= 8,
                letter: /[a-zA-Z]/.test(password),
                number: /\d/.test(password)
            };
            
            // 更新UI显示
            const lengthEl = document.getElementById('req-length');
            const letterEl = document.getElementById('req-letter');
            const numberEl = document.getElementById('req-number');
            
            if (lengthEl) {
                lengthEl.className = 'requirement-item ' + (requirements.length ? 'valid' : 'invalid');
            }
            if (letterEl) {
                letterEl.className = 'requirement-item ' + (requirements.letter ? 'valid' : 'invalid');
            }
            if (numberEl) {
                numberEl.className = 'requirement-item ' + (requirements.number ? 'valid' : 'invalid');
            }
            
            return requirements.length && requirements.letter && requirements.number;
        }
        
        // 绑定密码输入事件
        document.addEventListener('DOMContentLoaded', function() {
            const passwordInput = document.getElementById('registerPassword');
            if (passwordInput) {
                passwordInput.addEventListener('input', function() {
                    validatePassword(this.value);
                });
            }
        });

        // 注册
        async function register() {
            const username = document.getElementById('registerUsername').value.trim();
            const email = document.getElementById('registerEmail').value.trim();
            const password = document.getElementById('registerPassword').value;
            const confirmPassword = document.getElementById('registerConfirmPassword').value;

            if (!username || !email || !password || !confirmPassword) {
                showAuthError('请填写完整的注册信息');
                return;
            }

            // 收集所有验证错误
            const validationErrors = [];
            
            // 验证用户名格式
            if (username.length < 3 || username.length > 80) {
                validationErrors.push('用户名需要3-80个字符');
            }
            
            if (!/^[a-zA-Z0-9_-]+$/.test(username)) {
                validationErrors.push('用户名只能包含字母、数字、下划线和连字符');
            }
            
            // 验证邮箱格式
            const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
            if (!emailRegex.test(email)) {
                validationErrors.push('邮箱格式不正确，请输入有效的邮箱地址');
            }
            
            // 验证密码强度
            if (!validatePassword(password)) {
                const passwordErrors = [];
                if (password.length < 8) {
                    passwordErrors.push('密码至少需要8个字符');
                }
                if (!/[a-zA-Z]/.test(password)) {
                    passwordErrors.push('密码必须包含字母');
                }
                if (!/\d/.test(password)) {
                    passwordErrors.push('密码必须包含数字');
                }
                validationErrors.push(...passwordErrors);
            }

            if (password !== confirmPassword) {
                validationErrors.push('两次输入的密码不一致');
            }
            
            // 如果有验证错误，显示所有错误
            if (validationErrors.length > 0) {
                showAuthError('注册信息验证失败：', validationErrors);
                return;
            }

            try {
                const response = await fetch('/api/auth/register', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ username, email, password })
                });

                const data = await response.json();

                if (data.success) {
                    authToken = data.token;
                    localStorage.setItem('authToken', authToken);
                    currentUser = data.user;
                    updateUserInfo();
                    showMainApp();
                } else {
                    // 处理服务器返回的错误信息
                    let errorMessage = data.message || '注册失败';
                    let errorDetails = null;
                    
                    // 如果服务器返回了详细的错误信息
                    if (data.errors && Array.isArray(data.errors)) {
                        errorDetails = data.errors;
                    } else if (data.details && Array.isArray(data.details)) {
                        errorDetails = data.details;
                    }
                    
                    // 根据常见错误类型提供更友好的提示
                    if (errorMessage.includes('用户名已存在') || errorMessage.includes('username already exists')) {
                        errorMessage = '用户名已被使用，请选择其他用户名';
                    } else if (errorMessage.includes('邮箱已存在') || errorMessage.includes('email already exists')) {
                        errorMessage = '邮箱已被注册，请使用其他邮箱或尝试登录';
                    } else if (errorMessage.includes('密码强度不足') || errorMessage.includes('password')) {
                        errorMessage = '密码不符合要求';
                        if (!errorDetails) {
                            errorDetails = ['密码必须至少8个字符，包含字母和数字'];
                        }
                    }
                    
                    showAuthError(errorMessage, errorDetails);
                }
            } catch (error) {
                console.error('注册失败:', error);
                showAuthError('网络连接失败，请检查网络后重试');
            }
        }

        // 退出登录
        function logout() {
            localStorage.removeItem('authToken');
            authToken = null;
            currentUser = null;
            if (abortController) {
                abortController.abort();
                abortController = null;
            }
            showAuthContainer();
        }

        // 更新用户信息
         function updateUserInfo(user = null, stats = null) {
             const userToUpdate = user || currentUser;
             if (userToUpdate) {
                 // 更新用户头像
                 const userAvatar = document.getElementById('userAvatar');
                 if (userAvatar) {
                     userAvatar.textContent = userToUpdate.username.charAt(0).toUpperCase();
                 }
                 
                 // 更新欢迎信息
                 const welcomeMessage = document.getElementById('welcomeMessage');
                 if (welcomeMessage) {
                     const displayName = userToUpdate.email || userToUpdate.username;
                     welcomeMessage.innerHTML = `Welcome to CREbio, <strong>${displayName}</strong>! 👋`;
                 }
                 
                 // 余额显示已移除
                 
                 // 更新配额信息
                 const quotaInfo = document.getElementById('quotaInfo');
                 if (quotaInfo) {
                     if (stats) {
                         const weeklyUsed = stats.weekly_requests_used || 0;
                         const weeklyLimit = stats.weekly_requests_limit || userToUpdate.weekly_request_limit || 50;
                         const remaining = Math.max(0, weeklyLimit - weeklyUsed);
                         quotaInfo.innerHTML = `Weekly quota: <span class="text-primary">${remaining}/${weeklyLimit}</span> requests remaining (renews 2025-08-25)`;
                     } else {
                         // 如果没有统计数据，显示加载中
                         quotaInfo.innerHTML = `Weekly quota: <span class="text-muted">Loading...</span>`;
                     }
                 }
             }
         }

         // 更新底部计费统计的函数
        function updateBillingStats(user, statistics, costSummary) {
            // 更新本周调用次数
            const weeklyRequestsEl = document.getElementById('weeklyRequests');
            const weeklyLimitEl = document.getElementById('weeklyLimit');
            if (weeklyRequestsEl && weeklyLimitEl) {
                weeklyRequestsEl.textContent = statistics.weekly_requests_used || 0;
                weeklyLimitEl.textContent = statistics.weekly_requests_limit || user.weekly_request_limit || 50;
            }
            
            // 更新输入Tokens
            const inputTokensEl = document.getElementById('inputTokens');
            if (inputTokensEl) {
                inputTokensEl.textContent = (statistics.total_input_tokens || 0).toLocaleString();
            }
            
            // 更新输出Tokens
            const outputTokensEl = document.getElementById('outputTokens');
            if (outputTokensEl) {
                outputTokensEl.textContent = (statistics.total_output_tokens || 0).toLocaleString();
            }
            
            // 更新总Token使用
            const totalTokensEl = document.getElementById('totalTokens');
            if (totalTokensEl) {
                const totalTokens = (statistics.total_input_tokens || 0) + (statistics.total_output_tokens || 0);
                totalTokensEl.textContent = totalTokens.toLocaleString();
            }
            
            // 计算并更新API元点消耗
            const apiPointsEl = document.getElementById('apiPoints');
            if (apiPointsEl) {
                const inputTokens = statistics.total_input_tokens || 0;
                const outputTokens = statistics.total_output_tokens || 0;
                const apiPoints = (inputTokens / 26.6) + (outputTokens / 133.2);
                apiPointsEl.textContent = apiPoints.toFixed(2);
            }
            
            // 更新总费用
            const totalCostEl = document.getElementById('totalCost');
            if (totalCostEl) {
                totalCostEl.textContent = (costSummary?.total_cost || 0).toFixed(4);
            }
            
            // 移除了本次会话费用的更新逻辑
            
            // 更新平均每次调用费用
            const avgCostEl = document.getElementById('avgCost');
            if (avgCostEl) {
                const totalQueries = statistics.total_queries || 0;
                const avgCost = totalQueries > 0 ? (costSummary?.total_cost || 0) / totalQueries : 0;
                avgCostEl.textContent = avgCost.toFixed(4);
            }
        }

        // 显示配置标签
        function showConfigTab(tabName) {
            // 隐藏所有标签内容
            document.querySelectorAll('.config-content').forEach(content => {
                content.classList.remove('active');
            });
            document.querySelectorAll('.config-tab').forEach(tab => {
                tab.classList.remove('active');
            });

            // 显示选中的标签
            document.getElementById(tabName + 'Config').classList.add('active');
            event.target.classList.add('active');
        }

        // 测试API连接
        async function testConnection() {
            const apiKey = document.getElementById('apiKey').value.trim();
            const baseUrl = document.getElementById('baseUrl').value.trim();
            const statusIndicator = document.getElementById('apiStatus');
            
            if (!apiKey) {
                addSystemMessage('请先输入 API Key');
                return;
            }
            
            statusIndicator.className = 'status-indicator pending ms-auto';
            statusIndicator.innerHTML = '<i class="fas fa-circle"></i> 测试中...';
            
            try {
                const response = await fetch('/api/test-connection', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${authToken}`
                    },
                    body: JSON.stringify({
                        api_key: apiKey,
                        base_url: baseUrl
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    statusIndicator.className = 'status-indicator connected ms-auto';
                    statusIndicator.innerHTML = '<i class="fas fa-circle"></i> 已连接';
                    addSystemMessage('API 连接测试成功！');
                } else {
                    statusIndicator.className = 'status-indicator disconnected ms-auto';
                    statusIndicator.innerHTML = '<i class="fas fa-circle"></i> 连接失败';
                    addSystemMessage('API 连接测试失败: ' + (data.message || '未知错误'));
                }
            } catch (error) {
                statusIndicator.className = 'status-indicator disconnected ms-auto';
                statusIndicator.innerHTML = '<i class="fas fa-circle"></i> 连接失败';
                addSystemMessage('连接测试失败，请检查网络');
            }
        }

        // 保存高级配置
        function saveAdvancedConfig() {
            const config = {
                timeout: document.getElementById('timeout').value,
                retryCount: document.getElementById('retryCount').value,
                requestInterval: document.getElementById('requestInterval').value,
                concurrentLimit: document.getElementById('concurrentLimit').value,
                debugMode: document.getElementById('debugMode').value,
                logLevel: document.getElementById('logLevel').value,
                saveConversation: document.getElementById('saveConversation').checked,
                performanceMonitor: document.getElementById('performanceMonitor').checked,
                contentFilter: document.getElementById('contentFilter').checked,
                encryptApiKey: document.getElementById('encryptApiKey').checked
            };
            
            localStorage.setItem('advancedConfig', JSON.stringify(config));
            addSystemMessage('高级配置已保存');
        }

        // 重置高级配置
        function resetAdvancedConfig() {
            document.getElementById('timeout').value = '30';
            document.getElementById('retryCount').value = '3';
            document.getElementById('requestInterval').value = '100';
            document.getElementById('concurrentLimit').value = '5';
            document.getElementById('debugMode').value = 'false';
            document.getElementById('logLevel').value = 'INFO';
            document.getElementById('saveConversation').checked = true;
            document.getElementById('performanceMonitor').checked = false;
            document.getElementById('contentFilter').checked = true;
            document.getElementById('encryptApiKey').checked = true;
            
            localStorage.removeItem('advancedConfig');
            addSystemMessage('高级配置已重置为默认值');
        }

        // 导出配置
        function exportConfig() {
            const config = {
                api: {
                    baseUrl: document.getElementById('baseUrl').value,
                    dataPath: document.getElementById('dataPath').value
                },
                model: {
                    llmModel: document.querySelector('input[name="model"]:checked')?.value || 'claude-sonnet-4-20250514',
                    temperature: document.getElementById('temperature').value,
                    maxTokens: document.getElementById('maxTokens').value,
                    topP: document.getElementById('topP')?.value || '1',
                    frequencyPenalty: document.getElementById('frequencyPenalty')?.value || '0',
                    presencePenalty: document.getElementById('presencePenalty')?.value || '0'
                },
                advanced: JSON.parse(localStorage.getItem('advancedConfig') || '{}')
            };
            
            const blob = new Blob([JSON.stringify(config, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'biomni-config.json';
            a.click();
            URL.revokeObjectURL(url);
            
            addSystemMessage('配置已导出');
        }

        // 导入配置
        function importConfig() {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = '.json';
            input.onchange = function(e) {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        try {
                            const config = JSON.parse(e.target.result);
                            
                            // 导入API配置
                            if (config.api) {
                                if (config.api.baseUrl) document.getElementById('baseUrl').value = config.api.baseUrl;
                                if (config.api.dataPath) document.getElementById('dataPath').value = config.api.dataPath;
                            }
                            
                            // 导入模型配置
                            if (config.model) {
                                if (config.model.llmModel) {
                                    const modelRadio = document.querySelector(`input[name="model"][value="${config.model.llmModel}"]`);
                                    if (modelRadio) modelRadio.checked = true;
                                }
                                if (config.model.temperature) {
                                    document.getElementById('temperature').value = config.model.temperature;
                                    document.getElementById('temperatureValue').textContent = config.model.temperature;
                                }
                                if (config.model.maxTokens) document.getElementById('maxTokens').value = config.model.maxTokens;
                            }
                            
                            // 导入高级配置
                            if (config.advanced) {
                                localStorage.setItem('advancedConfig', JSON.stringify(config.advanced));
                                loadAdvancedConfig();
                            }
                            
                            addSystemMessage('配置导入成功');
                        } catch (error) {
                            addSystemMessage('配置文件格式错误');
                        }
                    };
                    reader.readAsText(file);
                }
            };
            input.click();
        }

        // 加载高级配置
        function loadAdvancedConfig() {
            const config = JSON.parse(localStorage.getItem('advancedConfig') || '{}');
            
            if (config.timeout) document.getElementById('timeout').value = config.timeout;
            if (config.retryCount) document.getElementById('retryCount').value = config.retryCount;
            if (config.requestInterval) document.getElementById('requestInterval').value = config.requestInterval;
            if (config.concurrentLimit) document.getElementById('concurrentLimit').value = config.concurrentLimit;
            if (config.debugMode) document.getElementById('debugMode').value = config.debugMode;
            if (config.logLevel) document.getElementById('logLevel').value = config.logLevel;
            if (config.saveConversation !== undefined) document.getElementById('saveConversation').checked = config.saveConversation;
            if (config.performanceMonitor !== undefined) document.getElementById('performanceMonitor').checked = config.performanceMonitor;
            if (config.contentFilter !== undefined) document.getElementById('contentFilter').checked = config.contentFilter;
            if (config.encryptApiKey !== undefined) document.getElementById('encryptApiKey').checked = config.encryptApiKey;
        }

        // 初始化代理
        async function initializeAgent() {
            const apiKey = document.getElementById('apiKey').value.trim();
            const baseUrl = document.getElementById('baseUrl').value.trim();
            const dataPath = document.getElementById('dataPath').value.trim();
            // 获取选中的模型
            const selectedModel = document.querySelector('input[name="model"]:checked');
            const llmModel = selectedModel ? selectedModel.value : 'claude-sonnet-4-20250514';

            if (!apiKey) {
                addSystemMessage('请先配置 API Key');
                return;
            }

            try {
                updateStatus('processing', '初始化中...');
                
                const response = await fetch('/api/initialize', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${authToken}`
                    },
                    body: JSON.stringify({
                        api_key: apiKey,
                        base_url: baseUrl,
                        llm_model: llmModel,
                        data_path: dataPath
                    })
                });

                const data = await response.json();
                
                if (data.success) {
                    isAgentInitialized = true;
                    updateStatus('ready', '已初始化');
                    document.getElementById('copilotSendButton').disabled = false;
                    addSystemMessage('代理初始化成功！现在可以开始对话了。');
                } else {
                    updateStatus('error', '初始化失败');
                    addSystemMessage('初始化失败: ' + (data.message || '未知错误'));
                }
            } catch (error) {
                console.error('初始化失败:', error);
                updateStatus('error', '初始化失败');
                addSystemMessage('初始化请求失败，请检查网络连接');
            }
        }

        // 重置代理
        async function resetAgent() {
            try {
                const response = await fetch('/api/reset', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${authToken}`
                    }
                });
                
                const data = await response.json();
                
                if (data.success) {
                    isAgentInitialized = false;
                    updateStatus('', '未初始化');
                    document.getElementById('copilotSendButton').disabled = true;
                    document.getElementById('copilotMessages').innerHTML = `
                        <div class="message system">
                            代理已重置。请重新配置并初始化。
                        </div>
                    `;
                    clearSummary();
                    // 移除了会话成本重置逻辑
                    currentSessionId = null; // 重置会话ID，开始新对话
                    console.log('已重置会话ID，开始新对话');
                    fetchUserStats(); // 更新统计信息
                }
            } catch (error) {
                console.error('重置失败:', error);
                addSystemMessage('重置失败，请重试');
            }
        }

        // Co-pilot发送消息函数
        async function sendCopilotMessage() {
            const input = document.getElementById('copilotInput');
            const message = input.value.trim();

            if (!message) {
                return;
            }

            if (!isAgentInitialized) {
                addCopilotSystemMessage('请先初始化代理');
                return;
            }

            // 检查配额限制
            const quotaInfo = document.getElementById('quotaInfo');
            if (quotaInfo) {
                const quotaText = quotaInfo.textContent;
                const remainingMatch = quotaText.match(/(\d+)\/(\d+)/);
                if (remainingMatch) {
                    const remaining = parseInt(remainingMatch[1]);
                    if (remaining <= 0) {
                        addCopilotSystemMessage('本周请求次数已用完，请等待下周重置或联系管理员');
                        return;
                    }
                }
            }

            // 添加用户消息到Co-pilot
            addCopilotUserMessage(message);
            input.value = '';

            // 禁用发送按钮
            document.getElementById('copilotSendButton').disabled = true;
            updateStatus('processing', '处理中...');
            
            // 添加处理提示
            addExecutionMessage('<div class="text-muted"><i class="fas fa-spinner fa-spin me-2"></i>正在处理您的请求...</div>', 'info');

            await executeQuery(message);
        }

        // 执行查询的核心函数
        async function executeQuery(message) {
            try {
                // 创建AbortController用于取消请求
                abortController = new AbortController();
                
                // 获取选中的模型
                const selectedModel = document.querySelector('input[name="model"]:checked');
                const modelValue = selectedModel ? selectedModel.value : 'claude-sonnet-4-20250514';
                
                // 使用 fetch 进行流式请求
                let url = `/api/query?query=${encodeURIComponent(message)}&model=${modelValue}`;
                if (currentSessionId) {
                    url += `&session_id=${currentSessionId}`;
                    console.log('发送消息到现有会话:', currentSessionId);
                } else {
                    console.log('发送消息到新会话');
                }
                const response = await fetch(url, {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${authToken}`,
                        'Accept': 'text/event-stream',
                        'Cache-Control': 'no-cache'
                    },
                    signal: abortController.signal
                });
                
                if (!response.ok) {
                    if (response.status === 429) {
                        // 配额超限错误
                        const errorData = await response.json().catch(() => ({}));
                        const errorMessage = errorData.message || '本周请求次数已用完，请等待下周重置';
                        addCopilotSystemMessage(errorMessage);
                        addExecutionMessage(`<div class="text-warning"><i class="fas fa-exclamation-triangle me-2"></i>配额限制: ${errorMessage}</div>`, 'warning');
                        updateStatus('ready', '已初始化');
                        document.getElementById('copilotSendButton').disabled = false;
                        fetchUserStats(); // 更新配额显示
                        return;
                    }
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const reader = response.body.getReader();
                const decoder = new TextDecoder();

                let assistantMessageId = 'copilot-assistant-' + Date.now();
                let assistantMessageAdded = false;
                let buffer = '';
                let intelligentSummary = null;

                // 处理流式响应
                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;
                    
                    buffer += decoder.decode(value, { stream: true });
                    const lines = buffer.split('\n');
                    buffer = lines.pop(); // 保留最后一个不完整的行
                    
                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            try {
                                const data = JSON.parse(line.slice(6));
                                
                                // 统一处理session_id更新
                                if (data.session_id && !currentSessionId) {
                                    currentSessionId = data.session_id;
                                    console.log('Updated currentSessionId from response:', currentSessionId);
                                }
                                
                                if (data.type === 'message') {
                                    if (!assistantMessageAdded) {
                                        addCopilotAssistantMessage('', assistantMessageId);
                                        assistantMessageAdded = true;
                                    }
                                    appendToCopilotMessage(assistantMessageId, data.content);
                                } else if (data.type === 'log') {
                                    // 处理日志消息 - 显示在执行面板
                                    addExecutionMessage(`<div class="log-message">📝 ${data.content}</div>`, 'log');
                                } else if (data.type === 'reasoning') {
                                    // 处理推理消息 - 显示在执行面板
                                    addExecutionMessage(`<div class="reasoning-message">🤔 <strong>推理:</strong> ${data.content}</div>`, 'reasoning');
                                } else if (data.type === 'execution') {
                                    // 处理执行消息 - 显示在执行面板
                                    const codeType = data.code_type || 'python';
                                    addExecutionMessage(`<div class="execution-code">⚙️ <strong>执行 ${codeType.toUpperCase()}:</strong><pre><code class="language-${codeType}">${data.content}</code></pre></div>`, 'execution');
                                } else if (data.type === 'observation') {
                                    // 处理观察消息 - 显示在执行面板
                                    addExecutionMessage(`<div class="observation-message">👁️ <strong>观察:</strong> ${data.content}</div>`, 'observation');
                                } else if (data.type === 'solution') {
                    // 处理解决方案消息 - 显示在Co-pilot
                    if (!assistantMessageAdded) {
                        addCopilotAssistantMessage('', assistantMessageId);
                        assistantMessageAdded = true;
                    }
                    appendToCopilotMessage(assistantMessageId, `<div class="solution-message">💡 <strong>解决方案:</strong> ${data.content}</div>`);
                                } else if (data.type === 'task_start') {
                                    // 处理任务开始消息 - 显示在执行面板
                                    addExecutionMessage(`<div class="task-start-message">🚀 ${data.content}</div>`, 'task');
                                } else if (data.type === 'resource_retrieval') {
                                    // 处理资源检索消息 - 显示在执行面板
                                    addExecutionMessage(`<div class="resource-retrieval-message">🔍 ${data.content}</div>`, 'resource');
                                } else if (data.type === 'agent_start') {
                                    // 处理代理启动消息 - 显示在执行面板
                                    addExecutionMessage(`<div class="agent-start-message">⚙️ ${data.content}</div>`, 'agent');
                                } else if (data.type === 'planning') {
                                    // 处理规划消息 - 显示在执行面板
                                    addExecutionMessage(`<div class="planning-message">📋 <strong>规划:</strong> ${data.content}</div>`, 'planning');
                                } else if (data.type === 'summary') {
                                    // 保存基础总结数据
                                    addSummaryItem(data.content);
                                } else if (data.type === 'intelligent_summary') {
                                    // 保存智能总结
                                    intelligentSummary = data.content;
                                } else if (data.type === 'warning') {
                                    // 处理警告消息 - 显示在执行面板
                                    addExecutionMessage(`<div class="text-warning"><i class="fas fa-exclamation-triangle me-2"></i>${data.content}</div>`, 'warning');
                                } else if (data.type === 'info') {
                                    // 处理信息消息 - 显示在执行面板
                                    addExecutionMessage(`<div class="text-info"><i class="fas fa-info-circle me-2"></i>${data.content}</div>`, 'info');
                                } else if (data.type === 'complete') {
                                    abortController = null;
                                    updateStatus('ready', '已初始化');
                                    document.getElementById('copilotSendButton').disabled = false;
                                    
                                    // 显示智能总结
                                    if (intelligentSummary) {
                                        if (!assistantMessageAdded) {
                                            addCopilotAssistantMessage('', assistantMessageId);
                                            assistantMessageAdded = true;
                                        }
                                        
                                        // 格式化智能总结显示
                                        let summaryHtml = '';
                                        if (typeof intelligentSummary === 'object') {
                                            summaryHtml = `
                                                <div class="intelligent-summary">
                                                    <h5>📊 执行总结</h5>
                                                    <div class="summary-details">
                                                        <p><strong>查询:</strong> ${intelligentSummary.query || '未知'}</p>
                                                        <p><strong>执行时间:</strong> ${intelligentSummary.execution_time || '0'}秒</p>
                                                        <p><strong>总步骤:</strong> ${intelligentSummary.total_steps || 0}</p>
                                                        <p><strong>成功步骤:</strong> ${intelligentSummary.successful_steps || 0}</p>
                                                        ${intelligentSummary.failed_steps > 0 ? `<p><strong>失败步骤:</strong> ${intelligentSummary.failed_steps}</p>` : ''}
                                                        <p><strong>状态:</strong> <span class="badge ${intelligentSummary.status === 'completed' ? 'bg-success' : 'bg-warning'}">${intelligentSummary.status === 'completed' ? '完成' : '部分成功'}</span></p>
                                                        ${intelligentSummary.actions && intelligentSummary.actions.length > 0 ? `
                                                            <div class="mt-2">
                                                                <strong>主要操作:</strong>
                                                                <ul class="list-unstyled mt-1">
                                                                    ${intelligentSummary.actions.map(action => `<li>• ${action}</li>`).join('')}
                                                                </ul>
                                                            </div>
                                                        ` : ''}
                                                        <p class="text-muted small mt-2">Token使用: ${intelligentSummary.total_tokens || 0} | 预估费用: $${intelligentSummary.total_cost || '0.0000'}</p>
                                                    </div>
                                                </div>
                                            `;
                                        } else {
                                            summaryHtml = `<div class="intelligent-summary">📊 <strong>执行总结:</strong><br>${intelligentSummary}</div>`;
                                        }
                                        
                                        appendToCopilotMessage(assistantMessageId, summaryHtml);
                                    }
                                    
                                    // 更新会话成本
                                    if (intelligentSummary && intelligentSummary.total_cost) {
                                        // 移除了会话成本累加逻辑，改为使用全局统计
                                    }
                                    
                                    addExecutionMessage('<div class="text-success"><i class="fas fa-check-circle me-2"></i>任务执行完成</div>', 'success');
                                    fetchUserStats(); // 更新用户统计信息
                                    return;
                                } else if (data.type === 'heartbeat') {
                                    // 心跳包，不需要处理，只是保持连接
                                    continue;
                                } else if (data.type === 'error') {
                                    abortController = null;
                                    addCopilotSystemMessage('错误: ' + data.content);
                                    addExecutionMessage(`<div class="text-danger"><i class="fas fa-exclamation-triangle me-2"></i>执行出错: ${data.content}</div>`, 'error');
                                    updateStatus('ready', '已初始化');
                                    document.getElementById('copilotSendButton').disabled = false;
                                    return;
                                }
                            } catch (error) {
                                console.error('解析响应失败:', error);
                            }
                        }
                    }
                }
                
                // 流结束后的清理
                abortController = null;
                updateStatus('ready', '已初始化');
                document.getElementById('copilotSendButton').disabled = false;
                fetchUserStats();

            } catch (error) {
                console.error('执行查询失败:', error);
                abortController = null;
                if (error.name !== 'AbortError') {
                    addCopilotSystemMessage('执行失败，请重试');
                    addExecutionMessage(`<div class="text-danger"><i class="fas fa-exclamation-triangle me-2"></i>连接失败: ${error.message}</div>`, 'error');
                }
                updateStatus('ready', '已初始化');
                document.getElementById('copilotSendButton').disabled = false;
            }
        }

        // 兼容性函数：原有的sendMessage函数
        async function sendMessage() {
            await sendCopilotMessage();
        }

        // Co-pilot回车键处理
        function handleCopilotKeyPress(event) {
            if (event.key === 'Enter' && !event.shiftKey) {
                event.preventDefault();
                sendCopilotMessage();
            }
        }

        // 兼容性函数：原有的回车键处理
        function handleKeyPress(event) {
            handleCopilotKeyPress(event);
        }

        // 复制示例问题到输入框
        function copyExampleToInput(element) {
            const exampleText = element.textContent.trim();
            const inputElement = document.getElementById('copilotInput');
            
            if (inputElement && exampleText) {
                inputElement.value = exampleText;
                inputElement.focus();
                
                // 更新复杂度指示器
                updateComplexityIndicator();
                
                // 添加视觉反馈
                element.style.backgroundColor = '#e8f5e8';
                setTimeout(() => {
                    element.style.backgroundColor = '';
                }, 300);
                
                // 滚动到输入框位置
                inputElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
        }

        // 更新复杂度指示器
        function updateComplexityIndicator() {
            const input = document.getElementById('copilotInput');
            const indicator = document.getElementById('complexityIndicator');
            const indicatorIcon = document.getElementById('indicatorIcon');
            const indicatorText = document.getElementById('indicatorText');
            const indicatorDesc = document.getElementById('indicatorDesc');
            
            const query = input.value.trim();
            
            if (query.length === 0) {
                indicator.style.display = 'none';
                return;
            }
            
            // 简化的复杂度判断逻辑（与后端保持一致）
            const isSimple = isSimpleConversation(query);
            
            indicator.style.display = 'block';
            indicator.className = 'complexity-indicator ' + (isSimple ? 'simple' : 'complex');
            
            if (isSimple) {
                indicatorIcon.className = 'indicator-icon fas fa-comments';
                indicatorText.textContent = '简单对话模式';
                indicatorDesc.textContent = '快速响应，适合问候和简单问题';
            } else {
                indicatorIcon.className = 'indicator-icon fas fa-cogs';
                indicatorText.textContent = '复杂任务模式';
                indicatorDesc.textContent = '启动工作流执行器，适合复杂分析任务';
            }
        }
        
        // 简化的对话类型判断函数（前端版本）
        function isSimpleConversation(query) {
            query = query.toLowerCase();
            
            // 问候语和礼貌用语
            const greetings = ['你好', 'hello', 'hi', '嗨', '您好', '早上好', '下午好', '晚上好', '谢谢', 'thank you', 'thanks', '再见', 'bye', 'goodbye'];
            
            // 复杂关键词
            const complexKeywords = ['analyze', '分析', 'predict', '预测', 'model', '建模', 'simulate', '模拟', 'calculate', '计算', 'design', '设计', 'optimize', '优化', 'search', '搜索', 'find', '查找', 'compare', '比较', 'evaluate', '评估', 'generate', '生成', 'create', '创建', 'build', '构建', 'develop', '开发', 'implement', '实现', 'execute', '执行', 'run', '运行', 'process', '处理', 'extract', '提取', 'transform', '转换'];
            
            // 检查问候语
            for (const greeting of greetings) {
                if (query.includes(greeting)) {
                    return true;
                }
            }
            
            // 检查查询长度
            if (query.length < 10) {
                return true;
            }
            
            // 检查复杂关键词
            for (const keyword of complexKeywords) {
                if (query.includes(keyword)) {
                    return false;
                }
            }
            
            // 简单问题
            const simpleQuestions = ['什么是', 'what is', 'what are', '如何', 'how to', 'how do', '为什么', 'why', '哪里', 'where', '什么时候', 'when', '谁', 'who', '多少', 'how much', 'how many'];
            for (const question of simpleQuestions) {
                if (query.includes(question)) {
                    return query.length <= 50;
                }
            }
            
            // 默认：长查询为复杂任务
            return query.length <= 100;
        }

        // 更新状态
        function updateStatus(status, text) {
            const statusDot = document.getElementById('statusDot');
            const statusText = document.getElementById('statusText');
            
            statusDot.className = 'status-dot';
            if (status) {
                statusDot.classList.add(status);
            }
            statusText.textContent = text;
        }

        // Co-pilot消息处理函数
        function addCopilotUserMessage(content) {
            console.log('addCopilotUserMessage被调用，内容:', content.substring(0, 100) + '...');
            const messagesContainer = document.getElementById('copilotMessages');
            console.log('copilotMessages容器:', messagesContainer);
            if (!messagesContainer) {
                console.error('找不到copilotMessages容器!');
                return;
            }
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message user';
            messageDiv.textContent = content;
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
            console.log('用户消息已添加，当前消息数量:', messagesContainer.children.length);
        }

        function addCopilotAssistantMessage(content, messageId) {
            console.log('addCopilotAssistantMessage被调用，内容:', content.substring(0, 100) + '...');
            const messagesContainer = document.getElementById('copilotMessages');
            console.log('copilotMessages容器:', messagesContainer);
            if (!messagesContainer) {
                console.error('找不到copilotMessages容器!');
                return;
            }
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message assistant';
            messageDiv.id = messageId;
            messageDiv.innerHTML = content.replace(/\n/g, '<br>');
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
            console.log('助手消息已添加，当前消息数量:', messagesContainer.children.length);
        }

        function addCopilotSystemMessage(content) {
            const messagesContainer = document.getElementById('copilotMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message system';
            messageDiv.textContent = content;
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
            return messageDiv;
        }

        // 执行面板消息处理函数
        function addExecutionMessage(content, type = 'info') {
            const messagesContainer = document.getElementById('executionMessages');
            
            // 如果是第一条消息，清除占位符
            if (messagesContainer.querySelector('.text-center')) {
                messagesContainer.innerHTML = '';
            }
            
            const messageDiv = document.createElement('div');
            messageDiv.className = `execution-message ${type}`;
            
            // 智能处理换行符：如果内容包含 <pre> 标签，则不处理换行符；否则转换换行符为 <br>
            if (content.includes('<pre>') || content.includes('<code>')) {
                messageDiv.innerHTML = content;
            } else {
                messageDiv.innerHTML = content.replace(/\n/g, '<br>');
            }
            
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

        // 原有的消息函数保持不变（用于兼容）
        function addUserMessage(content) {
            addCopilotUserMessage(content);
        }

        function addAssistantMessage(content, messageId) {
            addCopilotAssistantMessage(content, messageId);
        }

        function addSystemMessage(content) {
            return addCopilotSystemMessage(content);
        }

        // 追加到Co-pilot消息
        function appendToCopilotMessage(messageId, content) {
            const messageDiv = document.getElementById(messageId);
            if (messageDiv) {
                const currentContent = messageDiv.innerHTML;
                messageDiv.innerHTML = currentContent + content.replace(/\n/g, '<br>');
                const messagesContainer = document.getElementById('copilotMessages');
                messagesContainer.scrollTop = messagesContainer.scrollHeight;
            }
        }

        // 追加到消息（兼容性函数）
        function appendToMessage(messageId, content) {
            appendToCopilotMessage(messageId, content);
        }

        // 添加总结项
        function addSummaryItem(summaryData) {
            const summaryContainer = document.getElementById('summaryContent');
            
            // 如果是第一个总结，清除占位符
            if (summaryContainer.querySelector('.text-center')) {
                summaryContainer.innerHTML = '';
            }

            const summaryDiv = document.createElement('div');
            summaryDiv.className = 'summary-item';
            
            const title = document.createElement('div');
            title.className = 'summary-title';
            title.textContent = summaryData.query_preview || '执行总结';
            
            const stats = document.createElement('div');
            stats.className = 'summary-stats';
            
            const statsData = [
                { label: '步骤', value: summaryData.total_steps || 0 },
                { label: '时间', value: (summaryData.execution_time || 0) + 's' },
                { label: 'Token', value: summaryData.total_tokens || 0 },
                { label: '费用', value: '¥' + (summaryData.total_cost || '0.00') }
            ];
            
            statsData.forEach(stat => {
                const statDiv = document.createElement('div');
                statDiv.className = 'summary-stat';
                statDiv.innerHTML = `
                    <div class="summary-stat-value">${stat.value}</div>
                    <div class="summary-stat-label">${stat.label}</div>
                `;
                stats.appendChild(statDiv);
            });
            
            summaryDiv.appendChild(title);
            summaryDiv.appendChild(stats);
            summaryContainer.appendChild(summaryDiv);
            
            // 滚动到最新的总结
            summaryContainer.scrollTop = summaryContainer.scrollHeight;
        }

        // 清除总结
        function clearSummary() {
            const summaryContainer = document.getElementById('summaryContent');
            summaryContainer.innerHTML = `
                <div class="text-center text-muted py-4">
                    <i class="fas fa-inbox fa-2x mb-2"></i>
                    <div>暂无执行记录</div>
                </div>
            `;
        }

        // 获取用户统计信息
        async function fetchUserStats() {
            try {
                const response = await fetch('/api/user/profile', {
                    headers: {
                        'Authorization': `Bearer ${authToken}`
                    }
                });
                
                if (response.ok) {
                    const data = await response.json();
                    if (data.success && data.user && data.statistics) {
                        // 更新顶部用户信息
                        updateUserInfo(data.user, {
                            account_balance: data.user.balance,
                            weekly_requests_used: data.statistics.weekly_requests_used || 0,
                            weekly_requests_limit: data.statistics.weekly_requests_limit || data.user.weekly_request_limit || 50
                        });
                        
                        // 更新底部计费统计
                        updateBillingStats(data.user, data.statistics, data.cost_summary);
                    }
                }
            } catch (error) {
                console.error('获取统计信息失败:', error);
            }
        }

        // 会话管理相关函数
        async function loadAvailableSessions() {
            console.log('开始加载会话历史，使用token:', authToken ? '存在' : '不存在');
            try {
                const response = await fetch('/api/conversations', {
                    headers: {
                        'Authorization': `Bearer ${authToken}`
                    }
                });
                
                console.log('会话历史API响应状态:', response.status);
                
                if (response.ok) {
                    const data = await response.json();
                    console.log('会话历史API返回数据:', data);
                    const sessionSelect = document.getElementById('sessionSelect');
                    
                    // 清空现有选项
                    sessionSelect.innerHTML = '<option value="">Select a Session to Download Logs</option>';
                    
                    // 添加会话选项
                    if (data.success && data.conversations && data.conversations.length > 0) {
                        console.log('找到', data.conversations.length, '个会话记录');
                        let latestConversationId = null;
                        
                        data.conversations.forEach((conversation, index) => {
                            const option = document.createElement('option');
                            option.value = conversation.id;
                            
                            // 构建显示文本，包含执行记录信息
                            let displayText = `${conversation.created_at} - ${conversation.query_summary ? conversation.query_summary.substring(0, 50) : 'No summary'}...`;
                            
                            // 如果有执行记录，添加标识
                            if (conversation.has_execution_data && conversation.execution_count > 0) {
                                displayText += ` [执行记录: ${conversation.execution_count}个]`;
                            }
                            
                            option.textContent = displayText;
                            sessionSelect.appendChild(option);
                            
                            // 记录第一个（最新的）会话ID
                            if (index === 0) {
                                latestConversationId = conversation.id;
                            }
                        });
                        
                        // 不自动选择会话，让用户手动选择
                    } else {
                        console.log('没有找到会话记录或数据格式不正确');
                    }
                } else {
                    console.error('加载会话列表失败，状态码:', response.status);
                    const errorText = await response.text();
                    console.error('错误详情:', errorText);
                }
            } catch (error) {
                console.error('加载会话列表出错:', error);
            }
        }
        
        function onSessionSelected() {
            const sessionSelect = document.getElementById('sessionSelect');
            const sessionActions = document.getElementById('sessionActions');
            
            if (sessionSelect.value) {
                sessionActions.style.display = 'block';
            } else {
                sessionActions.style.display = 'none';
            }
        }
        
        async function downloadSession() {
            const sessionSelect = document.getElementById('sessionSelect');
            const sessionId = sessionSelect.value;
            
            if (!sessionId) {
                addSystemMessage('请先选择一个会话');
                return;
            }
            
            try {
                const response = await fetch('/api/conversations/download', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${authToken}`
                    },
                    body: JSON.stringify({
                        conversation_ids: [parseInt(sessionId)]
                    })
                });
                
                if (response.ok) {
                    const data = await response.json();
                    if (data.success && data.download_url) {
                        // 使用返回的下载链接进行实际文件下载
                        const downloadResponse = await fetch(data.download_url, {
                            headers: {
                                'Authorization': `Bearer ${authToken}`
                            }
                        });
                        
                        if (downloadResponse.ok) {
                            const blob = await downloadResponse.blob();
                            const url = window.URL.createObjectURL(blob);
                            const a = document.createElement('a');
                            a.style.display = 'none';
                            a.href = url;
                            a.download = data.filename || `conversation_${sessionId}.zip`;
                            document.body.appendChild(a);
                            a.click();
                            window.URL.revokeObjectURL(url);
                            document.body.removeChild(a);
                            addSystemMessage('会话下载成功');
                        } else {
                            addSystemMessage('下载文件失败，请重试');
                        }
                    } else {
                        addSystemMessage('获取下载链接失败: ' + (data.message || '未知错误'));
                    }
                } else {
                    const errorData = await response.json();
                    addSystemMessage('下载失败: ' + (errorData.message || '未知错误'));
                }
            } catch (error) {
                console.error('下载会话出错:', error);
                addSystemMessage('下载失败，请重试');
            }
        }
        
        async function loadSessionHistory() {
            const sessionSelect = document.getElementById('sessionSelect');
            const sessionId = sessionSelect.value;
            
            if (!sessionId) {
                addSystemMessage('请先选择一个会话');
                return;
            }
            
            // 注意：这里的sessionId是conversation.id，我们需要从API返回中获取真正的session_id
            console.log('正在加载会话ID:', sessionId);
            
            try {
                const response = await fetch(`/api/conversations/${sessionId}/content`, {
                    headers: {
                        'Authorization': `Bearer ${authToken}`
                    }
                });
                
                if (response.ok) {
                    const data = await response.json();
                    console.log('loadSessionHistory API返回数据:', data);
                    if (data.success && data.conversation_content) {
                    const content = data.conversation_content;
                        console.log('会话内容:', content);
                        
                        // 设置当前会话ID为真正的session_id
                        currentSessionId = content.session_id;
                        console.log('设置当前会话ID为:', currentSessionId);
                        
                        // 清空当前聊天记录
                        const copilotMessagesContainer = document.getElementById('copilotMessages');
                        console.log('copilotMessages容器:', copilotMessagesContainer);
                        if (copilotMessagesContainer) {
                            copilotMessagesContainer.innerHTML = '';
                            console.log('已清空聊天记录');
                        } else {
                            console.error('找不到copilotMessages容器!');
                        }
                        
                        // 优先显示log_data中的所有历史消息
                        if (content.log_data && content.log_data.length > 0) {
                            console.log('从log_data加载', content.log_data.length, '条历史消息');
                            content.log_data.forEach((message, index) => {
                                if (message.query) {
                                    console.log(`添加历史用户消息 ${index + 1}:`, message.query.substring(0, 100) + '...');
                                    addUserMessage(message.query);
                                }
                                if (message.response) {
                                    console.log(`添加历史助手消息 ${index + 1}:`, message.response.substring(0, 100) + '...');
                                    const historyMessageId = 'history-message-' + message.request_id + '-' + index;
                                    addAssistantMessage(message.response, historyMessageId);
                                }
                            });
                        } else {
                            // 如果没有log_data，则使用旧格式的query_text和response_text
                            if (content.query_text) {
                                console.log('添加用户消息:', content.query_text.substring(0, 100) + '...');
                                addUserMessage(content.query_text);
                            }
                            if (content.response_text) {
                                console.log('添加助手消息:', content.response_text.substring(0, 100) + '...');
                                const historyMessageId = 'history-message-' + Date.now();
                                addAssistantMessage(content.response_text, historyMessageId);
                            }
                        }
                        
                        console.log('添加完成消息');
                        addSystemMessage(`已加载完整历史会话: ${content.created_at}`);
                        
                        // 检查是否有执行记录数据
                        if (content.has_execution_data && content.execution_count > 0) {
                            console.log('检测到执行记录数据，数量:', content.execution_count);
                            addSystemMessage(`此会话包含 ${content.execution_count} 个复杂问题的执行记录`);
                            
                            // 尝试加载执行记录详情
                            try {
                                console.log('正在加载执行记录，conversation_id:', sessionId);
                                const execResponse = await fetch(`/api/conversations/${sessionId}`, {
                                    headers: {
                                        'Authorization': `Bearer ${authToken}`
                                    }
                                });
                                
                                if (execResponse.ok) {
                                    const execData = await execResponse.json();
                                    console.log('API返回的完整数据:', execData);
                                    console.log('conversation数据:', execData.conversation);
                                    if (execData.success && execData.conversation && execData.conversation.execution_files) {
                                        console.log('执行记录详情:', execData.conversation.execution_files);
                                        
                                        // 显示执行记录摘要
                                        execData.conversation.execution_files.forEach((execFile, index) => {
                                            const execInfo = `执行记录 ${index + 1}: 查询ID ${execFile.query_id}, ${execFile.step_count} 个步骤, 耗时 ${execFile.execution_time}s`;
                                            const execMessage = addSystemMessage(execInfo + ' [点击查看详情]');
                                            
                                            // 添加可点击样式和点击事件
                                            execMessage.classList.add('clickable');
                                            execMessage.addEventListener('click', async () => {
                                                await showExecutionDetails(sessionId, execFile.query_id);
                                            });
                                        });
                                        
                                        // 不自动显示执行记录详情，让用户点击查看
                                    } else {
                                        console.log('没有找到execution_files数据');
                                        console.log('execData.success:', execData.success);
                                        console.log('execData.conversation存在:', !!execData.conversation);
                                        if (execData.conversation) {
                                            console.log('execution_files存在:', !!execData.conversation.execution_files);
                                            console.log('execution_files内容:', execData.conversation.execution_files);
                                        }
                                    }
                                }
                            } catch (execError) {
                                console.error('加载执行记录详情失败:', execError);
                            }
                        }
                        
                        // 检查聊天容器中的消息数量
                        const chatMessages = document.getElementById('copilotMessages');
                        console.log('聊天容器中的消息数量:', chatMessages.children.length);
                        console.log('聊天容器HTML:', chatMessages.innerHTML.substring(0, 200) + '...');
                    } else {
                        addSystemMessage('加载历史失败: ' + (data.message || '未知错误'));
                    }
                } else {
                    addSystemMessage('加载历史失败，请重试');
                }
            } catch (error) {
                console.error('加载历史出错:', error);
                addSystemMessage('加载历史失败，请重试');
            }
        }

        // 显示执行记录详细信息
        async function showExecutionDetails(conversationId, queryId) {
            try {
                console.log('获取执行记录详情:', conversationId, queryId);
                const authToken = localStorage.getItem('authToken');
                const response = await fetch(`/api/conversations/${conversationId}/execution/${queryId}`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${authToken}`
                    }
                });
                
                if (response.ok) {
                    const data = await response.json();
                    if (data.success && data.execution_data) {
                        displayExecutionDetails(data.execution_data, queryId);
                    } else {
                        addSystemMessage('获取执行记录详情失败: ' + (data.message || '未知错误'));
                    }
                } else {
                    addSystemMessage('获取执行记录详情失败，请重试');
                }
            } catch (error) {
                console.error('获取执行记录详情出错:', error);
                addSystemMessage('获取执行记录详情失败，请重试');
            }
        }
        
        // 显示执行记录详细信息
        function displayExecutionDetails(executionData, queryId) {
            console.log('显示执行记录详情:', executionData);
            console.log('查询ID:', queryId);
            console.log('详细步骤数据:', executionData.detailed_steps);
            console.log('基本步骤数据:', executionData.steps);
            
            // 创建详细信息的HTML
            let detailsHtml = `<div class="execution-details" style="background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 8px; padding: 15px; margin: 10px 0;">`;
            detailsHtml += `<h4 style="color: #495057; margin-bottom: 15px;">执行记录详情 - 查询ID: ${queryId}</h4>`;
            
            if (executionData.query_text) {
                detailsHtml += `<div style="margin-bottom: 10px;"><strong>查询内容:</strong> ${executionData.query_text}</div>`;
            }
            
            // 优先显示详细步骤数据（从steps_文件加载）
            if (executionData.detailed_steps && executionData.detailed_steps.length > 0) {
                detailsHtml += `<div style="margin-bottom: 10px;"><strong>详细执行步骤 (${executionData.detailed_steps.length}个):</strong></div>`;
                detailsHtml += `<ol style="margin-left: 20px;">`;
                
                executionData.detailed_steps.forEach((step, index) => {
                    detailsHtml += `<li style="margin-bottom: 12px; border-left: 3px solid #007bff; padding-left: 10px;">`;
                    detailsHtml += `<strong>步骤 ${index + 1}:</strong> ${step.step_type || '未知类型'}`;
                    
                    if (step.content) {
                        const formattedContent = step.content.replace(/\n/g, '<br>').replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;');
                        detailsHtml += `<br><div style="color: #495057; font-size: 0.9em; margin-top: 5px;"><strong>内容:</strong><br><pre style="background: #f8f9fa; padding: 8px; border-radius: 4px; margin: 5px 0; white-space: pre-wrap; font-family: 'Courier New', monospace; font-size: 0.85em; max-height: 400px; overflow-y: auto;">${formattedContent}</pre></div>`;
                    }
                    
                    if (step.formatted_output) {
                        const formattedOutput = step.formatted_output.replace(/\n/g, '<br>').replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;');
                        detailsHtml += `<br><div style="color: #28a745; font-size: 0.9em; margin-top: 5px;"><strong>输出:</strong><br><pre style="background: #e8f5e8; padding: 8px; border-radius: 4px; margin: 5px 0; white-space: pre-wrap; font-family: 'Courier New', monospace; font-size: 0.85em; max-height: 400px; overflow-y: auto;">${formattedOutput}</pre></div>`;
                    }
                    
                    if (step.tool_calls && step.tool_calls.length > 0) {
                        detailsHtml += `<br><span style="color: #6f42c1; font-size: 0.9em;">工具调用: ${step.tool_calls.length}个</span>`;
                    }
                    
                    if (step.error) {
                        detailsHtml += `<br><span style="color: #dc3545; font-size: 0.9em;">错误: ${step.error}</span>`;
                    }
                    
                    if (step.timestamp) {
                        detailsHtml += `<br><span style="color: #6c757d; font-size: 0.8em;">时间: ${step.timestamp}</span>`;
                    }
                    detailsHtml += `</li>`;
                });
                
                detailsHtml += `</ol>`;
            }
            // 如果没有详细步骤，显示基本步骤信息
            else if (executionData.steps && executionData.steps.length > 0) {
                detailsHtml += `<div style="margin-bottom: 10px;"><strong>基本执行步骤 (${executionData.steps.length}个):</strong></div>`;
                detailsHtml += `<ol style="margin-left: 20px;">`;
                
                executionData.steps.forEach((step, index) => {
                    detailsHtml += `<li style="margin-bottom: 8px;">`;
                    detailsHtml += `<strong>步骤 ${index + 1}:</strong> ${step.action || '未知操作'}`;
                    if (step.result) {
                        const formattedResult = step.result.replace(/\n/g, '<br>').replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;');
                        detailsHtml += `<br><div style="color: #6c757d; font-size: 0.9em; margin-top: 5px;"><strong>结果:</strong><br><pre style="background: #f8f9fa; padding: 8px; border-radius: 4px; margin: 5px 0; white-space: pre-wrap; font-family: 'Courier New', monospace; font-size: 0.85em; max-height: 400px; overflow-y: auto;">${formattedResult}</pre></div>`;
                    }
                    if (step.timestamp) {
                        detailsHtml += `<br><span style="color: #6c757d; font-size: 0.8em;">时间: ${step.timestamp}</span>`;
                    }
                    detailsHtml += `</li>`;
                });
                
                detailsHtml += `</ol>`;
            }
            
            // 显示中间步骤信息
            if (executionData.intermediate_steps && executionData.intermediate_steps.length > 0) {
                detailsHtml += `<div style="margin-top: 15px; margin-bottom: 10px;"><strong>中间步骤 (${executionData.intermediate_steps.length}个):</strong></div>`;
                detailsHtml += `<div style="background: #fff; border: 1px solid #e9ecef; border-radius: 4px; padding: 10px; max-height: 200px; overflow-y: auto;">`;
                
                executionData.intermediate_steps.forEach((step, index) => {
                    detailsHtml += `<div style="margin-bottom: 8px; padding: 5px; border-bottom: 1px solid #f8f9fa;">`;
                    const stepContent = JSON.stringify(step, null, 2);
                    const formattedStepContent = stepContent.replace(/\n/g, '<br>').replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;').replace(/ /g, '&nbsp;');
                    detailsHtml += `<strong>中间步骤 ${index + 1}:</strong><br><pre style="background: #f1f3f4; padding: 6px; border-radius: 3px; margin: 3px 0; white-space: pre-wrap; font-family: 'Courier New', monospace; font-size: 0.8em; max-height: 300px; overflow-y: auto;">${formattedStepContent}</pre>`;
                    detailsHtml += `</div>`;
                });
                
                detailsHtml += `</div>`;
            }
            
            if (executionData.total_cost) {
                detailsHtml += `<div style="margin-top: 10px;"><strong>总成本:</strong> $${executionData.total_cost}</div>`;
            }
            
            if (executionData.execution_time) {
                detailsHtml += `<div><strong>执行时间:</strong> ${executionData.execution_time}秒</div>`;
            }
            
            if (executionData.detailed_step_count) {
                detailsHtml += `<div><strong>详细步骤数量:</strong> ${executionData.detailed_step_count}个</div>`;
            }
            
            detailsHtml += `</div>`;
            
            // 添加到右侧执行记录面板
            const executionMessages = document.getElementById('executionMessages');
            
            if (!executionMessages) {
                console.error('找不到执行记录面板元素');
                addSystemMessage('显示执行记录详情失败：找不到执行面板');
                return;
            }
            
            console.log('找到执行记录面板，准备显示详情');
            
            // 清空现有内容
            executionMessages.innerHTML = '';
            
            // 创建执行详情容器
            const detailsDiv = document.createElement('div');
            detailsDiv.className = 'execution-details-container';
            detailsDiv.innerHTML = detailsHtml;
            executionMessages.appendChild(detailsDiv);
            
            // 滚动到顶部以显示详情
            executionMessages.scrollTop = 0;
        }

        // 文件上传相关函数
        function toggleFileUpload() {
            const section = document.getElementById('fileUploadSection');
            const btn = document.getElementById('fileToggleBtn');
            
            if (section.style.display === 'none') {
                section.style.display = 'block';
                btn.classList.add('active');
                refreshFileList();
            } else {
                section.style.display = 'none';
                btn.classList.remove('active');
            }
        }

        function handleDragOver(event) {
            event.preventDefault();
            event.stopPropagation();
            const uploadArea = document.getElementById('fileUploadArea');
            uploadArea.classList.add('drag-over');
        }

        function handleDragLeave(event) {
            event.preventDefault();
            event.stopPropagation();
            const uploadArea = document.getElementById('fileUploadArea');
            uploadArea.classList.remove('drag-over');
        }

        function handleFileDrop(event) {
            event.preventDefault();
            event.stopPropagation();
            const uploadArea = document.getElementById('fileUploadArea');
            uploadArea.classList.remove('drag-over');
            
            const files = event.dataTransfer.files;
            if (files.length > 0) {
                uploadFiles(files);
            }
        }

        function handleFileSelect(event) {
            const files = event.target.files;
            if (files.length > 0) {
                uploadFiles(files);
            }
        }

        async function uploadFiles(files) {
            // 检查代理是否已初始化
            if (!isAgentInitialized) {
                addSystemMessage('代理未初始化，正在尝试自动初始化...');
                
                // 尝试检查自动初始化状态
                try {
                    const response = await fetch('/api/initialization/status');
                    if (response.ok) {
                        const data = await response.json();
                        if (data.success && data.auto_initialized) {
                            isAgentInitialized = true;
                            addSystemMessage('代理自动初始化成功，继续上传文件...');
                        } else {
                            addSystemMessage('代理未初始化，请先在配置面板中设置API Key并点击初始化按钮');
                            return;
                        }
                    } else {
                        addSystemMessage('无法检查代理状态，请先手动初始化代理');
                        return;
                    }
                } catch (error) {
                    addSystemMessage('检查代理状态失败，请先手动初始化代理');
                    return;
                }
            }
            
            const formData = new FormData();
            
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                
                // 检查文件大小（限制为50MB）
                if (file.size > 50 * 1024 * 1024) {
                    addSystemMessage(`文件 ${file.name} 太大，请选择小于50MB的文件`);
                    continue;
                }
                
                formData.append('file', file);
                
                try {
                    const response = await fetch('/agent/upload-file', {
                        method: 'POST',
                        headers: {
                            'Authorization': `Bearer ${authToken}`
                        },
                        body: formData
                    });
                    
                    const result = await response.json();
                    
                    if (result.success) {
                        addSystemMessage(`文件 ${file.name} 上传成功`);
                        
                        // 如果响应中包含新的session_id，更新当前session
                        if (result.session_id && result.session_id !== currentSessionId) {
                            currentSessionId = result.session_id;
                            console.log('Updated session_id after file upload:', currentSessionId);
                        }
                        
                        refreshFileList();
                    } else {
                        addSystemMessage(`文件 ${file.name} 上传失败: ${result.message}`);
                    }
                } catch (error) {
                    console.error('文件上传错误:', error);
                    addSystemMessage(`文件 ${file.name} 上传失败: ${error.message}`);
                }
                
                // 清空FormData以便下一个文件
                formData.delete('file');
            }
            
            // 清空文件输入
            document.getElementById('fileInput').value = '';
        }

        async function refreshFileList() {
            try {
                const response = await fetch('/agent/files', {
                    headers: {
                        'Authorization': `Bearer ${authToken}`
                    }
                });
                
                const result = await response.json();
                
                if (result.success) {
                    displayFileList(result.data.files);
                } else {
                    console.error('获取文件列表失败:', result.message);
                }
            } catch (error) {
                console.error('获取文件列表错误:', error);
            }
        }

        function displayFileList(files) {
            const fileList = document.getElementById('fileList');
            const fileItems = document.getElementById('fileItems');
            
            if (files.length === 0) {
                fileList.style.display = 'none';
                return;
            }
            
            fileList.style.display = 'block';
            fileItems.innerHTML = '';
            
            files.forEach(file => {
                const fileItem = document.createElement('div');
                fileItem.className = 'file-item';
                
                const fileIcon = getFileIcon(file.name);
                const fileSize = formatFileSize(file.size);
                
                fileItem.innerHTML = `
                    <div class="file-info">
                        <i class="${fileIcon} file-icon"></i>
                        <div class="file-details">
                            <div class="file-name">${file.name}</div>
                            <div class="file-size">${fileSize}</div>
                        </div>
                    </div>
                    <div class="file-actions">
                        <button class="btn-link btn-danger" onclick="deleteFile('${file.name}')">
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </div>
                `;
                
                fileItems.appendChild(fileItem);
            });
        }

        function getFileIcon(filename) {
            const ext = filename.split('.').pop().toLowerCase();
            const iconMap = {
                'csv': 'fas fa-file-csv',
                'json': 'fas fa-file-code',
                'txt': 'fas fa-file-alt',
                'pdf': 'fas fa-file-pdf',
                'png': 'fas fa-file-image',
                'jpg': 'fas fa-file-image',
                'jpeg': 'fas fa-file-image',
                'gif': 'fas fa-file-image',
                'xlsx': 'fas fa-file-excel',
                'xls': 'fas fa-file-excel',
                'fasta': 'fas fa-dna',
                'fastq': 'fas fa-dna',
                'vcf': 'fas fa-file-medical'
            };
            return iconMap[ext] || 'fas fa-file';
        }

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        async function deleteFile(filename) {
            if (!confirm(`确定要删除文件 ${filename} 吗？`)) {
                return;
            }
            
            try {
                const response = await fetch(`/agent/files/${encodeURIComponent(filename)}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${authToken}`
                    }
                });
                
                const result = await response.json();
                
                if (result.success) {
                    addSystemMessage(`文件 ${filename} 删除成功`);
                    refreshFileList();
                } else {
                    addSystemMessage(`删除文件失败: ${result.message}`);
                }
            } catch (error) {
                console.error('删除文件错误:', error);
                addSystemMessage(`删除文件失败: ${error.message}`);
            }
        }

        // 检查自动初始化状态
        async function checkAutoInitialization() {
            console.log('开始检查自动初始化状态...');
            try {
                // 不需要认证，直接检查初始化状态
                const response = await fetch('/api/initialization/status');
                console.log('API响应状态:', response.status);

                if (response.ok) {
                    const data = await response.json();
                    console.log('API返回数据:', data);
                    if (data.success && data.auto_initialized) {
                        console.log('检测到服务已自动初始化');
                        // 服务已自动初始化
                        isAgentInitialized = true;
                        
                        // 更新初始系统消息
                        const chatMessages = document.getElementById('copilotMessages');
                        console.log('chatMessages元素:', chatMessages);
                        if (chatMessages) {
                            const firstMessage = chatMessages.querySelector('.message.system');
                            console.log('firstMessage元素:', firstMessage);
                            if (firstMessage) {
                                const newContent = `欢迎更用CRE Bioinformatics Platfomm-AI Bian Que<br><br>✅ 服务已自动初始化完成！<br>模型: ${data.default_model}<br>${authToken ? '现在可以开始对话了。' : '请先登录以开始使用。'}`;
                                console.log('更新消息内容为:', newContent);
                                firstMessage.innerHTML = newContent;
                                console.log('消息已更新');
                            } else {
                                console.log('未找到.message.system元素');
                            }
                        } else {
                            console.log('未找到chatMessages元素');
                        }
                        
                        // 如果用户已登录且主应用界面可见，更新其他UI元素
                        if (authToken && document.getElementById('mainApp').style.display !== 'none') {
                            updateStatus('ready', '已自动初始化');
                            const sendButton = document.getElementById('copilotSendButton');
                            if (sendButton) sendButton.disabled = false;
                            
                            // 自动填充配置信息（显示当前使用的配置）
                            if (data.default_model) {
                                const modelRadio = document.querySelector(`input[name="model"][value="${data.default_model}"]`);
                                if (modelRadio) modelRadio.checked = true;
                            }
                            const dataPathInput = document.getElementById('dataPath');
                            if (dataPathInput && data.default_data_path) {
                                dataPathInput.value = data.default_data_path;
                            }
                            
                            // 显示提示信息
                            const configSection = document.querySelector('[onclick="toggleSection(\'config\')"');
                            if (configSection) {
                                configSection.innerHTML = '🔧 配置 (已自动配置)';
                            }
                        }
                        
                        console.log('服务已自动初始化:', data.default_model);
                    } else {
                        // 服务未自动初始化，需要手动配置
                        console.log('服务未自动初始化，需要手动配置');
                        
                        // 更新初始系统消息
                        const chatMessages = document.getElementById('copilotMessages');
                        if (chatMessages) {
                            const firstMessage = chatMessages.querySelector('.message.system');
                            if (firstMessage) {
                                firstMessage.innerHTML = `欢迎使用 CREbio 生物信息学研究平台！<br><br>⚠️ 系统尚未初始化。<br><br>${authToken ? '请在下方配置您的 API 设置后点击初始化按钮。' : '请先登录，然后配置 API 设置。'}`;
                            }
                        }
                        
                        if (authToken && document.getElementById('mainApp').style.display !== 'none') {
                            updateStatus('', '需要配置');
                        }
                    }
                } else {
                    console.error('检查初始化状态失败，状态码:', response.status);
                    if (response.status === 401) {
                        console.error('认证失败，可能需要重新登录');
                        // 清除无效token并显示登录界面
                        localStorage.removeItem('authToken');
                        authToken = null;
                        showAuthContainer();
                    }
                }
            } catch (error) {
                console.error('检查自动初始化状态失败:', error);
                // 在出错时也更新消息
                const chatMessages = document.getElementById('copilotMessages');
                if (chatMessages) {
                    const firstMessage = chatMessages.querySelector('.message.system');
                    if (firstMessage) {
                        firstMessage.innerHTML = `欢迎使用 CREbio 生物信息学研究平台！<br><br>⚠️ 无法检查系统状态。<br><br>请刷新页面重试或手动配置。`;
                    }
                }
            }
        }
    </script>
</body>
</html>